如何更改 HttpRequest 中的内容类型?

How to change Content type in HttpRequest?

这是我的代码:

public static void main(String[] args) throws Exception {
    HttpClient client = HttpClient.newHttpClient();

    File file = new File("/home/xxxxxxxxx/Téléchargements/XxxXx");
    File[] files = file.listFiles();

    for (File f : files) {
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://exemple.demo.monapi.com/api/v5/submissions"))
        .POST(BodyPublishers.ofFile(FileSystems.getDefault().getPath(f.getAbsolutePath())))
        .header("Authorization", "Token c0198efc82c36812a6a32af0579a8332aa37f7a7")
        .build();
        
        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
        System.out.println(response);
    }

}

问题是我得到了 415 响应,因为默认情况下内容类型是 application/pdf 并且支持的内容类型编码 POST 对我的 api 请求的主体是:

那么我该如何更改内容类型?

您可以通过添加多个.header("key", "value")来添加多个header。

内容类型 header 与授权 header 一起添加到下面的代码中

HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://exemple.demo.monapi.com/api/v5/submissions"))
        .POST(BodyPublishers.ofFile(FileSystems.getDefault().getPath(f.getAbsolutePath())))
        .header("Authorization", "Token c0198efc82c36812a6a32af0579a8332aa37f7a7")
        .header("Content-Type", "multipart/form-data")
        .build();