[英]In apache http client, how to keep the Content-Type in a StringBody as empty or null?
We have a restful API (which we cannot change) where if the Content-Type value for a part is null, we have a specific processing. 我们有一个宁静的API(无法更改),如果零件的Content-Type值为null,我们将进行特定处理。
Until httpclient3.x, we could do a the following and set the content type as null. 在httpclient3.x之前,我们可以执行以下操作并将内容类型设置为null。
StringPart sp = new StringPart("name, "value")
sp.setContentType(null);
Now, we have moved to http components (httpclient4.x jar) and I realised that we need to pass an instance of ContentBody (StringBody to be precise). 现在,我们转到了http组件(httpclient4.x jar),我意识到我们需要传递ContentBody的实例(准确地说是StringBody)。 Found the following 2 ways of doing the same in the new version:
在新版本中找到以下两种相同的方法:
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")));
However, I couldn't pass the body with no Content-Type. 但是,我无法通过没有Content-Type的正文。 Even if I use the deprecated constructor for StringBody, it sets the Content-Type to plain-text.
即使我对StringBody使用了不推荐使用的构造函数,它也会将Content-Type设置为纯文本。
I know that any part of a request should always have a Content-Type but this is a special case of an outdated destination server which we cannot upgrade. 我知道请求的任何部分都应该始终具有Content-Type,但这是过时的目标服务器的特殊情况,我们无法对其进行升级。
I think your only option is to use deprecated FormBodyPart#FormBodyPart(String name, ContentBody)
constructor AND to override deprecated FormBodyPart#generateContentType
method. 我认为您唯一的选择是使用不赞成使用的
FormBodyPart#FormBodyPart(String name, ContentBody)
构造函数,并重写不赞成使用的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);
std out > 标准输出>
--yJHqjnFj0u-dWGPGkGtK_NnOgUeOspQ
Content-Disposition: form-data; name="stuff"
Content-Transfer-Encoding: 8bit
stuff
--yJHqjnFj0u-dWGPGkGtK_NnOgUeOspQ--
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.