Question

I inherited some old code that uses the now-deprecated Apache Commons HttpClient. I was tasked with upgrading it to use the newer Apache HttpComponents. However, I can't seem to get this POST request to function properly. The server keeps complaining that Content-Length = 0. I'm fairly certain that it's a problem with my conversion of how parameters are added.

The old HttpClient code looks something like this:

PostMethod postMethod = null;
int responseCode = 0;
try{
    HttpClient httpClient = new HttpClient();
    postMethod = new PostMethod(getServiceUrl()); //The url, without a query.
    ...
    postMethod.addParameter(paramName, request);

    responseCode = httpClient.executeMethod(postMethod);
    ...
}

And here are my HttpComponents replacements:

HttpPost postMethod = null;
int responseCode = 0;
HttpResponse httpResponse = null;
try{
    HttpClient httpClient = new DefaultHttpClient();
    postMethod = new HttpPost(getServiceUrl()); //The url, without a query.
    ...
    BasicHttpParams params = new BasicHttpParams();
    params.setParameter(paramName, request);
    postMethod.setParams(params);

    httpResponse = httpClient.execute(postMethod);
    responseCode = httpResponse.getStatusLine().getStatusCode();
    ...
}

The servlet my code it talking to is using Apache Commons FileUpload. Here is the code it catches on when it receives my request:

ServletRequestContext src = new ServletRequestContext(request);
if (src.getContentLength() == 0)
    throw new IOException("Could not construct ServletRequestContext object");

It used to pass this test just fine. Now it doesn't. I've tried all kinds of alternatives, such as using the header, or passing request as a URLEncoded query. Have I made a mistake in my upgrade, somewhere?

Note: I can't just change how the servlet receives my request, because then I'll have to change a number of other apps that talk to it, and that's too big a job.

Was it helpful?

Solution

To set the request body, you can use HttpPost's setEntity() method. You can explore the available entity types here. This would replace the BasicHttpParams code.

To send a form entity, for example:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://someurl");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("name", "value"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(formEntity);
HttpResponse httpResponse = client.execute(httpPost);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top