我正在尝试使用 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% 确定这不是服务器端问题,因为我可以使用其他客户端,例如 Advanced Rest Client/Postman,它们可以毫无问题地发送图像。
你能帮我查明哪里出了问题吗?谢谢你。
原文由 asdt11 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 HttpClient 来计算这段代码。使用稳定的库总是比从头开始处理更好,除非有一些东西需要以自定义方式处理。