使用 java HTTP POST 连接发送图像文件
我正在尝试使用Java HTTP POST请求将图像发送到网站。
我正在使用这里使用的基本代码 将文件从Java客户端上传到HTTP服务器:
这是我的修改:
String urlToConnect = "http://localhost:9000/upload";
File fileToUpload = new File("C:\\Users\\joao\\Pictures\\bla.jpg");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true); // This sets request method to POST.
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream()));
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"picture\"; filename=\"bla.jpg\"");
writer.println("Content-Type: image/jpeg");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileToUpload)));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200
我最终得到了一个200响应代码,但图像是错误的,就像随机颜色一样,这让我认为这是字符编码的错误。我尝试使用原始示例中的UTF-8,但这只会创建一个损坏的图像。
我也100%确定这不是服务器端问题,因为我可以使用REST客户端,如Advanced Rest Client/Postman,他们可以毫无问题地发送图像。
你能帮我找出问题所在吗?谢谢。