How do I add Content-Length header to HttpPost within Apache HttpComponents?

user2265993 picture user2265993 · Apr 10, 2013 · Viewed 8.1k times · Source

I have a server which expects Content-Length as a part of POST header. For POSTing, I am using Apache HttpComponents library.

This is a stripped down version of the expected request (with all the required headers ofcourse):

POST /ParlayREST/1.0/sample/ HTTP/1.1
Content-Type: application/json
Accept: application/json
Host: server.url.com:8080
Content-Length: 287
{
    "listenerURL":"http://application.example.com/notifyURL"},
    "sessionId":"12345"
}

I have used the setEntity method of HttpPost to set a StringEntity (converted json -> String -> StringEntity) as content of the POST. But when I execute the request, I end up with a POST request which doesn't specify Content-length within it's header.

Is there anyway to add this missing header?

(I tried setHeader() to set the Content-Length which threw an error saying that the content length is already present)

This is the code that I am using to create the POST request:

//Convert the registration request object to json
StringEntity registrationRequest_json_entity = new StringEntity(gsonHandle.toJson(registrationRequest));
registrationRequest_json_entity.setContentType("application/json");

//Creating the HttpPost object which contains the endpoint URI
HttpPost httpPost = new HttpPost(Constants.CLIENT_REGISTRATION_URL);
httpPost.setHeader(HTTP.CONTENT_TYPE,"application/json");
httpPost.setHeader("Accept","application/json");
httpPost.setHeader(HTTP.TARGET_HOST,Constants.REGISTRATION_HOST + ":" + Constants.REGISTRATION_PORT);

//Set the content as enitity within the HttpPost object     
httpPost.setEntity(registrationRequest_json_entity);

HttpResponse response = httpClient.execute(httpPost, new BasicHttpContext());
HttpEntity entity = response.getEntity();
if (entity != null) {
    //work on the response
}
EntityUtils.consume(entity);

Answer

ok2c picture ok2c · Nov 5, 2019

HttpClient automatically generates Content-Length and Transfer-Encoding header values based on properties of the enclosed message entity and the actual protocol settings.

Do not set those headers manually.