我正在使用 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();
}
问题是服务器端需要文件的ContentType
为application/myCustomTag
但是,这不是 ContentType
接口(interface)中的值。我有什么方法可以提供自定义字符串作为 ContentType
吗?
编辑
我尝试重新创建浏览器上显示的请求
我的请求 header 为
[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]
我看到的主要区别是,在有效负载中,我在浏览器中看到以下内容
内容类型:application/myCustomTag
这不是 HTTP 标准 Content-Type
所以我无法这样设置
最佳答案
关于java - Apache HTTP : How to set custom ContentType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569655/