在 apache http 客户端中,如何将 StringBody 中的 Content-Type 保持为空或空? [英] In apache http client, how to keep the Content-Type in a StringBody as empty or null?

查看:49
本文介绍了在 apache http 客户端中,如何将 StringBody 中的 Content-Type 保持为空或空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 Restful API(我们无法更改),如果某个部分的 Content-Type 值为空,我们有一个特定的处理.

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.

在 httpclient3.x 之前,我们可以执行以下操作并将内容类型设置为 null.

Until httpclient3.x, we could do a the following and set the content type as null.

StringPart sp = new StringPart("name, "value")
sp.setContentType(null);

现在,我们已经转移到 http 组件(httpclient4.x jar),我意识到我们需要传递一个 ContentBody 实例(准确地说是 StringBody).在新版本中发现了以下两种方法:

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). 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")));

但是,我无法传递没有 Content-Type 的正文.即使我为 StringBody 使用不推荐使用的构造函数,它也会将 Content-Type 设置为纯文本.

However, I couldn't pass the body with no Content-Type. Even if I use the deprecated constructor for StringBody, it sets the Content-Type to plain-text.

我知道请求的任何部分都应该始终具有 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.

推荐答案

我认为你唯一的选择是使用已弃用的 FormBodyPart#FormBodyPart(String name, ContentBody) 构造函数 AND 覆盖已弃用的 FormBodyPart#generateContentType 方法.

I think your only option is to use deprecated FormBodyPart#FormBodyPart(String name, ContentBody) constructor AND to override deprecated FormBodyPart#generateContentType method.

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--

这篇关于在 apache http 客户端中,如何将 StringBody 中的 Content-Type 保持为空或空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆