我正在尝试使用带有POST方法的multipart上传文件,使用HTTPURLConnection。我收到406响应错误。
实际上我想使用HttpURLConnection将以下curl请求转换为java代码:
$ curl -i --header "Content-type: application/octet-stream" POST --data-binary "@pathToFile/inputFile.jar" http://username:password@hostname:port/resources?queryParams
这是返回的Java代码406响应:
public static void main(String[] args) throws Exception {
FileInputStream inputStreamToRuleAppArchive = null;
OutputStream outputStreamToRequestBody = null;
BufferedWriter httpRequestBodyWriter = null;
try{
// Connect to the web server endpoint
URL serverUrl =
new URL("hostname:port/resources");
HttpURLConnection urlConnection = (HttpURLConnection) serverUrl.openConnection();
String fileUrl = "inputFile.jar";
File logFileToUpload = new File(fileUrl);
// Indicate that we want to write to the HTTP request body
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Content-type", "application/octet-stream");
urlConnection.setDoInput(true);
String loginPassword = "username"+ ":" + "password";
String encoded = new sun.misc.BASE64Encoder().encode (loginPassword.getBytes());
urlConnection.setRequestProperty ("Authorization", "Basic " + encoded);
outputStreamToRequestBody = urlConnection.getOutputStream();
httpRequestBodyWriter =
new BufferedWriter(new OutputStreamWriter(outputStreamToRequestBody));
// Write the actual file contents
inputStreamToRuleAppArchive = new FileInputStream(logFileToUpload);
int bytesRead;
byte[] dataBuffer = new byte[1024];
while((bytesRead = inputStreamToRuleAppArchive.read(dataBuffer)) != -1) {
outputStreamToRequestBody.write(dataBuffer, 0, bytesRead);
}
urlConnection.connect();
// 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);
}
} finally{
// Close the streams
inputStreamToRuleAppArchive.close();
outputStreamToRequestBody.close();
httpRequestBodyWriter.close();
}
}
我在SO上搜索了许多其他问题并使用了这个MultiPartUtility类并面临同样的错误:http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically。