Search code examples
javahttpclient

Handling HttpClient Redirects


I'm POSTing some data to a server that is answering a 302 Moved Temporarily.

I want HttpClient to follow the redirect and automatically GET the new location, as I believe it's the default behaviour of HttpClient. However, I'm getting an exception and not following the redirect :(

Here's the relevant piece of code, any ideas will be appreciated:

HttpParams httpParams = new BasicHttpParams();
HttpClientParams.setRedirecting(httpParams, true);
SchemeRegistry schemeRegistry = registerFactories();
ClientConnectionManager clientConnectionManager = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

HttpClient httpClient = new DefaultHttpClient(clientConnectionManager, httpParams)
HttpPost postRequest = new HttpPost(url);
postRequest.setHeader(HTTP.CONTENT_TYPE, contentType);
postRequest.setHeader(ACCEPT, contentType);

if (requestBodyString != null) {
    postRequest.setEntity(new StringEntity(requestBodyString));
}

return httpClient.execute(postRequest, responseHandler);

Solution

  • The default behaviour of HttpClient is compliant with the requirements of the HTTP specification (RFC 2616)

    10.3.3 302 Found
    ...
    
       If the 302 status code is received in response to a request other
       than GET or HEAD, the user agent MUST NOT automatically redirect the
       request unless it can be confirmed by the user, since this might
       change the conditions under which the request was issued.
    
    

    You can override the default behaviour of HttpClient by sub-classing DefaultRedirectStrategy and overriding its #isRedirected() method.