【问题标题】:How to change Content type in HttpRequest?如何更改 HttpRequest 中的内容类型?
【发布时间】:2021-08-04 07:59:13
【问题描述】:

这是我的代码:

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,并且支持的用于对我的 api 的 POST 请求正文进行编码的内容类型是:

  • multipart/form-data(上传文件时常用)
  • application/x-www-form-urlencode(适用于所有剩余案例)

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

【问题讨论】:

    标签: java api httprequest


    【解决方案1】:

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

    内容类型标头与授权标头一起添加在下面的代码中

    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();
    

    【讨论】:

      猜你喜欢
      • 2018-05-20
      • 2010-10-29
      • 2012-09-22
      • 2018-08-30
      • 1970-01-01
      • 2010-10-31
      • 1970-01-01
      • 2016-12-07
      • 2012-09-22
      相关资源
      最近更新 更多