I would like to know how I can disable redirect for specific requests when using HttpClient. Right now, my client either allows or disables redirects for all its request. I want to be able to make some requests with redirects but some with redirect disable, all with the same client. Is it possible?
Example of using two clients (this is what I want to avoid):
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
public class MyClass {
public static void main(String[] args) throws Exception {
// Redirected client
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet("http://www.google.com");
client.execute(get);
// Non-redirected client
CloseableHttpClient client2 = HttpClientBuilder.create().disableRedirectHandling().build();
HttpGet get2 = new HttpGet("http://www.google.com");
client2.execute(get2);
}
}
To do this, open the Settings tab of your request and toggle off the Automatically follow redirects option. Force your request to follow the original HTTP method. To do so, open the Settings tab of the request and toggle on the Follow original HTTP method option.
CloseableHttpClient is an abstract class that represents a base implementation of the HttpClient interface. However, it also implements the Closeable interface. Thus, we should close all its instances after use.
HttpClient is fully thread-safe when used with a thread-safe connection manager such as MultiThreadedHttpConnectionManager.
Class LaxRedirectStrategyLax RedirectStrategy implementation that automatically redirects all HEAD, GET, POST, and DELETE requests. This strategy relaxes restrictions on automatic redirection of POST methods imposed by the HTTP specification.
You can implement your own RedirectStrategy
to handle redirection as you want and use setRedirectStrategy
of HttpClientBuilder
to let http client use your redirection strategy.
You can check DefaultRedirectStrategy and LaxRedirectStrategy implementations for reference.
Important part is isRedirected
method of RedirectStrategy
. You need to return true
or false
depending if you want to redirect specific request or not. Http request executor will be calling this method before doing actual redirection.
For example you can extend DefaultRedirectStrategy
and override isRedirected
method
...
public class MyRedirectStrategy extends DefaultRedirectStrategy {
...
@Override
public boolean isRedirected(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws ProtocolException {
// check request and return true or false to redirect or not
...
}
}
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