在 apache http 客户端中,如何将 StringBody 中的 Content-Type 保持为空或 null?
In apache http client, how to keep the Content-Type in a StringBody as empty or null?
我们有一个 restful API(我们无法更改),如果某个部分的 Content-Type 值为 null,我们将进行特定处理。
直到 httpclient3.x,我们可以执行以下操作并将内容类型设置为 null。
StringPart sp = new StringPart("name, "value")
sp.setContentType(null);
现在,我们已经转移到 http 组件 (httpclient4.x jar),我意识到我们需要传递一个 ContentBody 实例(准确地说是 StringBody)。在新版本中找到了以下两种方法:
multipartEntityBuilder.addPart(FormBodyPartBuilder.create().setName(propName).setBody(new StringBody(propValue, ContentType.create("application/octet-stream", "UTF-8"))).build());
multipartEntityBuilder.addPart(propName, new StringBody(propValue, ContentType.create("application/octet-stream", "UTF-8")));
但是,我无法传递没有 Content-Type 的正文。即使我对 StringBody 使用已弃用的构造函数,它也会将 Content-Type 设置为纯文本。
我知道请求的任何部分都应始终具有内容类型,但这是我们无法升级的过时目标服务器的特例。
我认为您唯一的选择是使用已弃用的 FormBodyPart#FormBodyPart(String name, ContentBody)
构造函数 AND 来覆盖已弃用的 FormBodyPart#generateContentType
方法。
FormBodyPart bodyPart = new FormBodyPart("stuff", new StringBody("stuff", ContentType.DEFAULT_TEXT)) {
@Override
protected void generateContentType(ContentBody body) {
}
};
HttpEntity entity = MultipartEntityBuilder.create().addPart(bodyPart).build();
entity.writeTo(System.out);
标准输出 >
--yJHqjnFj0u-dWGPGkGtK_NnOgUeOspQ
Content-Disposition: form-data; name="stuff"
Content-Transfer-Encoding: 8bit
stuff
--yJHqjnFj0u-dWGPGkGtK_NnOgUeOspQ--
我们有一个 restful API(我们无法更改),如果某个部分的 Content-Type 值为 null,我们将进行特定处理。
直到 httpclient3.x,我们可以执行以下操作并将内容类型设置为 null。
StringPart sp = new StringPart("name, "value")
sp.setContentType(null);
现在,我们已经转移到 http 组件 (httpclient4.x jar),我意识到我们需要传递一个 ContentBody 实例(准确地说是 StringBody)。在新版本中找到了以下两种方法:
multipartEntityBuilder.addPart(FormBodyPartBuilder.create().setName(propName).setBody(new StringBody(propValue, ContentType.create("application/octet-stream", "UTF-8"))).build());
multipartEntityBuilder.addPart(propName, new StringBody(propValue, ContentType.create("application/octet-stream", "UTF-8")));
但是,我无法传递没有 Content-Type 的正文。即使我对 StringBody 使用已弃用的构造函数,它也会将 Content-Type 设置为纯文本。
我知道请求的任何部分都应始终具有内容类型,但这是我们无法升级的过时目标服务器的特例。
我认为您唯一的选择是使用已弃用的 FormBodyPart#FormBodyPart(String name, ContentBody)
构造函数 AND 来覆盖已弃用的 FormBodyPart#generateContentType
方法。
FormBodyPart bodyPart = new FormBodyPart("stuff", new StringBody("stuff", ContentType.DEFAULT_TEXT)) {
@Override
protected void generateContentType(ContentBody body) {
}
};
HttpEntity entity = MultipartEntityBuilder.create().addPart(bodyPart).build();
entity.writeTo(System.out);
标准输出 >
--yJHqjnFj0u-dWGPGkGtK_NnOgUeOspQ
Content-Disposition: form-data; name="stuff"
Content-Transfer-Encoding: 8bit
stuff
--yJHqjnFj0u-dWGPGkGtK_NnOgUeOspQ--