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);
Redirect policy is set through the Builder. followRedirects method. Implementation Note: When automatic redirection occurs, the request method of the redirected request may be modified depending on the specific 30X status code, as specified in RFC 7231.
Java Http Redirect ExampleIf a server is redirected from the original URL to another URL, the response code should be 301: Moved Permanently or 302: Temporary Redirect. And you can get the new redirected url by reading the “Location” header of the HTTP response header.
You do not need to explicitly close the HttpClient, however, (you may be doing this already but worth noting) you should ensure that connections are released after method execution. Edit: The ClientConnectionManager within the HttpClient is going to be responsible for maintaining the state of connections.
A 301 redirect strategy enables you to gather the valuable link authority from discontinued URLs and shift it to live, relevant ones, giving your customers the next best option when the page they requested no longer exists.
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; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With