Monday, April 9, 2012

Handle defaulthttpclient redirects manually

By default DefaultHttpClient will handle redirect automatically. Sometimes we need to handle this manually, mainly if we need to set some parameters with every request.


We can do it by the following steps.
  1. Set HANDLE_REDIRECTS parameter value to false , that means it  defines redirects should be handled manually
HttpParams params = httpClient.getParams();
HttpClientParams.setRedirecting(params, false);
  1. Then after executing our request, if it is not HttpStatus.SC_OK or when response codes between 300 and 399 ( redirect responses )
    • Gets the values of the response header with the name as "Location"
    • the last value will be the new url where it need to redirect 
    • then execute the new request using the  redirect  url by setting the needed parameters
if (responseCode != HttpStatus.SC_OK) {
   Header[] headers = httpResponse.getHeaders("Location");
   if (headers != null && headers.length != 0) {
       String newUrl = headers[headers.length - 1].getValue();
     //Execute again with newUrl by setting the needed paramters
   }
}


My complete doHttpRequest method

private void doHttpRequest(String url){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(url);

        request.setParams(getHttpParams()); 
//getHttpParams is used to get the HttpParams 
//by setting all the required parameters

//Set HANDLE_REDIRECTS to false , 
//defines redirects should be handled manually
HttpParams params = httpClient.getParams();
HttpClientParams.setRedirecting(params, false);

HttpResponse httpResponse = 
httpClient.execute(request);

int responseCode = 
 httpResponse.getStatusLine().getStatusCode();


if (responseCode != HttpStatus.SC_OK) {
Header[] headers = 
httpResponse.getHeaders("Location");
if (headers != null && headers.length != 0) {
  //Need to redirect 
 String newUrl = 
    headers[headers.length - 1].getValue();

doHttpRequest(newUrl);
//call the doHttpRequest 
//recursively with new url
}
} else {
handleResponse(httpResponse);
}
}


Hope this help.
And please feel free to point out my mistakes...