I am not able to read multipart file from the http response. The response contains the MIME Boundary and content transfer encoding - binary. we need to read the date from the response and send the request to another http post method. here we are facing two issues.
- Not able to read the binary file properly from the http response.
- Not able to form the multipart file to send the request.
when I have send that multipart form data in http post method. I am not receiving proper response. beacuse of the multipart binary encoding file. please provide the sample to read the multipart binary file and how to form and send the multipart file.
private void postLocalRequest(URL url, byte[] requestBody, String contentType, String authHeader)
throws IOException, ProtocolException, Exception {
logger.info("local request URL:::" + url);
logger.info("local request content type:::" + contentType);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
if (!authHeader.isEmpty()) {
httpURLConnection.setRequestProperty("Authorization", authHeader);
}
httpURLConnection.addRequestProperty("Accept", "application/json; charset=UTF-8");
httpURLConnection.setRequestProperty("Content-Type", contentType);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(requestBody);
outputStream.flush();
logger.info("waiting for local response");
BufferedReader bufferedReader = null;
logger.info("http response code :::" + httpURLConnection.getResponseCode());
deviceResponse = "";
deviceResponseContentType = httpURLConnection.getContentType();
logger.info("device Response Content Type::" + deviceResponseContentType);
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
deviceResponse = bufferedReader.lines().collect(Collectors.joining("\n"));
XWCConnectorSupplementalLogging.logXML(logger, "plr", "Device Request Output", deviceResponse);
} else {
try {
InputStream ip = httpURLConnection.getInputStream();
String info = new BufferedReader(new InputStreamReader(ip)).lines().collect(Collectors.joining("\n"));
deviceResponse = info;
XWCConnectorSupplementalLogging.logXML(logger, "plr", "Device Request Output", info);
} catch (Exception e) {
try {
InputStream es = httpURLConnection.getErrorStream();
String error = new BufferedReader(new InputStreamReader(es)).lines()
.collect(Collectors.joining("\n"));
if(httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_NOT_FOUND) {
deviceResponse = error;
}
XWCConnectorSupplementalLogging.logXML(logger, "plr", "Device Request Error", error);
} catch (Exception e1) {
logger.severe("Unable to read Request error or output");
}
}
}
}