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.
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...
We can do it by the following steps.
- Set HANDLE_REDIRECTS parameter value to false , that means it defines redirects should be handled manually
HttpParams params = httpClient.getParams();
HttpClientParams.setRedirecting(params, false);
- 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
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...