Crusaderpyro Crusaderpyro - 9 months ago 45
reST (reStructuredText) Question

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.

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

StringPart sp = new StringPart("name, "value")

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

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.

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.

Answer Source

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

    protected void generateContentType(ContentBody body) {

HttpEntity entity = MultipartEntityBuilder.create().addPart(bodyPart).build();

std out >

Content-Disposition: form-data; name="stuff"
Content-Transfer-Encoding: 8bit