如何将文件写入 HTTP 请求 Java

How to write a file to an HTTP Request Java

我是 HTTP 的新手,我对在 Java 中将文件和另一个值写入 HTTP Post 请求有疑问。我正在使用一家名为 Mojang 的公司提供的 public API 将所谓的“皮肤”(png 文件)写入玩家角色模型的游戏 Minecraft。下面是如何使用这个publicAPI的文档供参考: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 = "\r\n";
    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();

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