【问题标题】:Apache HTTP : How to set custom ContentTypeApache HTTP:如何设置自定义 ContentType
【发布时间】:2017-06-15 14:06:22
【问题描述】:

我正在使用 apache http 客户端将文件上传为

public void whenSendMultipartRequestUsingHttpClient_thenCorrect() 
  throws ClientProtocolException, IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://www.example.com");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.addTextBody("ads", "John");
    builder.addTextBody("qwe", "pass");
    builder.addBinaryBody("file", new File("test.txt"),
      ContentType.APPLICATION_OCTET_STREAM, "file.ext");

    HttpEntity multipart = builder.build();
    httpPost.setEntity(multipart);

    CloseableHttpResponse response = client.execute(httpPost);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}

问题是服务器端需要文件的ContentTypeapplication/myCustomTag

但是,这不是ContentType 接口中的值。我有什么办法可以提供一个自定义字符串为ContentType

编辑

我尝试重新创建在浏览器上看到的请求

我的请求标头为

[X-head1: {someJson}, Accept: application/json, X-head2: someVal, X-head3: otherVal, Content-Type: application/json]

和有效载荷

[Content-Disposition: form-data; name="file.ext"; filename="test.txt", Content-Type: application/octet-stream, Content-Transfer-Encoding: binary]

我可以看到的主要区别是,在有效负载中,我在浏览器中看到以下内容

Content-Type: application/myCustomTag

这不是 HTTP 标准 Content-Type 所以我不能这样设置

【问题讨论】:

  • 您尝试过 ContentType.MULTIPART_FORM_DATA 吗?
  • httpPost.addHeader("Content-Type","'application/myCustomTag");怎么样
  • 谢谢,我试过了,但我仍然从服务器得到 500
  • @tsolakp 您的评论就是我一直在寻找的答案。

标签: java http mime-types apache-httpclient-4.x apache-httpcomponents


【解决方案1】:

您在 HttpPost 上尝试过 setHeader 吗? API here

替代方案:

ContentType.create("application/myCustomTag")

【讨论】:

  • 我用另一种方法编辑了我的答案。 (与 addBinaryBody 一起使用)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 2012-05-30
  • 2019-02-17
  • 1970-01-01
相关资源
最近更新 更多