Handling HttpClient Redirects

JavaHttpclient

Java Problem Overview


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);

Java Solutions


Solution 1 - Java

For HttpClient 4.3:

HttpClient instance = HttpClientBuilder.create()
                     .setRedirectStrategy(new LaxRedirectStrategy()).build();

For HttpClient 4.2:

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());

For HttpClient < 4.2:

DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new DefaultRedirectStrategy() {
    /** Redirectable methods. */
    private String[] REDIRECT_METHODS = new String[] { 
        HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME 
    };

    @Override
    protected boolean isRedirectable(String method) {
        for (String m : REDIRECT_METHODS) {
            if (m.equalsIgnoreCase(method)) {
                return true;
            }
        }
        return false;
    }
});

Solution 2 - Java

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.

Solution 3 - Java

It seem http redirect is disable by default. I try to enable, it work but I'm still got error with my problem. But we still can handle redirection pragmatically. I think your problem can solve: So old code:

AndroidHttpClient httpClient = AndroidHttpClient.newInstance("User-Agent");
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
long contentSize = httpResponse.getEntity().getContentLength();

This code will return contentSize = -1 if http redirect happend

And then I handle redirect by myself after trying enable default follow redirection

AndroidHttpClient client;
HttpGet httpGet;
HttpResponse response;
HttpHeader httpHeader;
private void handleHTTPRedirect(String url) throws IOException {
	if (client != null)
		client.close();

	client = AndroidHttpClient.newInstance("User-Agent");
	httpGet = new HttpGet(Network.encodeUrl(url));
	response = client.execute(httpGet);
	httpHeader = response.getHeaders("Location");
	while (httpHeader.length > 0) {
		client.close();
		client = AndroidHttpClient.newInstance("User-Agent");

		httpGet = new HttpGet(Network.encodeUrl(httpHeader[0].getValue()));
		response = client.execute(httpGet);
		httpHeader = response.getHeaders("Location");
	}
}

In use

handleHTTPRedirect(url);
long contentSize = httpResponse.getEntity().getContentLength();

Thanks Nguyen

Solution 4 - Java

My solution is using HttClient. I had to send the response back to the caller. This is my solution

	CloseableHttpClient httpClient = HttpClients.custom()
			.setRedirectStrategy(new LaxRedirectStrategy())
			.build();

	//this reads the input stream from POST
	ServletInputStream str = request.getInputStream();

	HttpPost httpPost = new HttpPost(path);
	HttpEntity postParams = new InputStreamEntity(str);
	httpPost.setEntity(postParams);

	HttpResponse httpResponse = null ;
	int responseCode = -1 ;
	StringBuffer response  = new StringBuffer();

	try {

		httpResponse = httpClient.execute(httpPost);

		responseCode = httpResponse.getStatusLine().getStatusCode();
		logger.info("POST Response Status::  {} for file {}  ", responseCode, request.getQueryString());

		//return httpResponse ;
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				httpResponse.getEntity().getContent()));

		String inputLine;
		while ((inputLine = reader.readLine()) != null) {
			response.append(inputLine);
		}
		reader.close();

		logger.info(" Final Complete Response {}  " + response.toString());
		httpClient.close();

	} catch (Exception e) {

		logger.error("Exception ", e);

	} finally {

		IOUtils.closeQuietly(httpClient);

	}

	// Return the response back to caller
	return 	new ResponseEntity<String>(response.toString(), HttpStatus.ACCEPTED);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmgvView Question on Stackoverflow
Solution 1 - JavaRTFView Answer on Stackoverflow
Solution 2 - Javaok2cView Answer on Stackoverflow
Solution 3 - JavaKhai NguyenView Answer on Stackoverflow
Solution 4 - JavavsinghView Answer on Stackoverflow