代码之家  ›  专栏  ›  技术社区  ›  birgersp

使用httpclient对具有相同客户端的特定请求禁用重定向

  •  6
  • birgersp  · 技术社区  · 6 年前

    我想知道在使用httpclient时如何禁用特定请求的重定向。现在,我的客户机允许或禁用其所有请求的重定向。我希望能够通过重定向发出一些请求,但是有些请求禁用重定向,所有请求都使用同一个客户机。有可能吗?

    使用两个客户机的示例(这是我想要避免的):

    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);
        }
    }
    
    1 回复  |  直到 6 年前
        1
  •  13
  •   miradham    6 年前

    你可以实现你自己的 RedirectStrategy 根据需要处理重定向并使用 setRedirectStrategy 属于 HttpClientBuilder 允许HTTP客户端使用重定向策略。

    你可以检查 DefaultRedirectStrategy LaxRedirectStrategy 供参考的实现。

    重要部分是 isRedirected 方法 重定向策略 . 你得回去 true false 取决于您是否要重定向特定的请求。HTTP请求执行器 will be calling 在执行实际重定向之前使用此方法。

    例如,您可以扩展 DefaultRedirectStrategy 超驰 重定向 方法

    ...
    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
        ...
        }
    }