Search code examples
javaresthttpclientapache-httpclient-4.xapache-commons-httpclient

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


Solution

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

    std out >

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