6

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);
    }
}
birgersp
  • 3,909
  • 8
  • 39
  • 79

1 Answers1

14

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
    ...
    }
}
miradham
  • 2,285
  • 16
  • 26