如何将文件写入HTTP请求Java



我是使用HTTP的新手,我有关于在Java中向HTTP Post请求写入文件和另一个值的问题。我正在使用Mojang公司提供的公共API来编写所谓的"皮肤"。(png文件)到游戏Minecraft的玩家角色模型。下面是如何使用这个公共API的文档供参考:https://wiki.vg/Mojang_API#Upload_Skin

这是我写的代码。当运行时,我得到415 HTTP响应代码(我假设这是"不支持的媒体类型")。我做错了什么,我怎么能解决这个问题的任何建议?我发现了上传文件的其他堆栈溢出问题,但我还需要添加一个名为"variant={classic or slim}"的值。我有点迷失在如何使所有这些工作。如有任何帮助,不胜感激。

(我无法在代码示例中使用' '正确格式化代码,它在javascript片段中)

public static void uploadSkin(String accessToken, String variant, File file) throws IOException {
URL url = new URL("https://api.minecraftservices.com/minecraft/profile/skins");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Bearer " + accessToken); // The access token is provided after an
  // authentication request has been send, I
  // have done this sucessfully in another
  // method and am passing it in here
con.addRequestProperty("variant", variant);

OutputStream outputStream = con.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(con.getOutputStream(), "utf-8"), true);
String boundary = "===" + System.currentTimeMillis() + "===";
String fileName = file.getName();
String LINE_FEED = "rn";
String fieldName = "file";
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name="" + fieldName + ""; filename="" + fileName + """)
.append(LINE_FEED);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}

好的,找到解决问题的方法了。使用maven依赖项:

<!-- https://mvnrepository.com/artifact/org.jodd/jodd-http -->
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-http</artifactId>
<version>5.0.2</version>
</dependency>

然后这个:

HttpResponse response = HttpRequest.post("https://api.minecraftservices.com/minecraft/profile/skins")
.header("Authorization", "Bearer " + accessToken).header("Content-Type", "multipart/form-data")
.form("variant", variant).form("file", file).send();

我能让它工作。希望这对任何需要上传皮肤Png文件到Minecraft的人有帮助。