我正在尝试使用 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,它们可以毫无问题地发送图像。
你能帮我找出问题所在吗?谢谢你。