我正在尝试将对multipart / form-data的POST请求转换为Java程序,并且收到java.io.IOException:服务器返回了HTTP响应代码:400
// Connect to the web server endpoint
URL serverUrl =
new URL("http://testurl/start-date/2017-01-01/upload");
HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection();
//String boundaryString = "----SomeRandomText";
String fileUrl = "C:/Users/V70070/Documents/ALL FILES/Rates/MAC2291_RATES.csv";
String encodedCredentials = "Basic dGVzdDpwYXNzd29yZA==";
File logFileToUpload = new File(fileUrl);
// Indicate that we want to write to the HTTP request body
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty ("Authorization", encodedCredentials);
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Content-Type", "multipart/form-data");
OutputStream outputStreamToRequestBody = urlConnection.getOutputStream();
BufferedWriter httpRequestBodyWriter =
new BufferedWriter(new OutputStreamWriter(outputStreamToRequestBody));
// Include value from the myFileDescription text area in the post data
httpRequestBodyWriter.write("Content-Disposition: form-data; name=\"fileData\"; Content-Type: text/plain; filename=\"MAC2291_RATES.csv\"");
// Include the section to describe the file
// httpRequestBodyWriter.write("Content-Disposition: form-data;"
// + "name=\"myFile\";"
// + "filename=\"" + logFileToUpload.getName() + "\""
// + "\nContent-Type: text/plain\n\n");
// httpRequestBodyWriter.flush();
// Write the actual file contents
FileInputStream inputStreamToLogFile = new FileInputStream(logFileToUpload);
int bytesRead;
byte[] dataBuffer = new byte[1024];
while ((bytesRead = inputStreamToLogFile.read(dataBuffer)) != -1) {
outputStreamToRequestBody.write(dataBuffer, 0, bytesRead);
}
outputStreamToRequestBody.flush();
// Mark the end of the multipart http request
//httpRequestBodyWriter.write("\n--" + boundaryString + "--\n");
httpRequestBodyWriter.flush();
// Read response from web server, which will trigger the multipart HTTP request to be sent.
BufferedReader httpResponseReader =
new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String lineRead;
while((lineRead = httpResponseReader.readLine()) != null) {
System.out.println(lineRead);
}
// Close the streams
outputStreamToRequestBody.close();
httpRequestBodyWriter.close();
}
从Web服务器读取响应时出现异常
BufferedReader httpResponseReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
任何帮助,我们将不胜感激。 TIA