HttpClient4.3.3 禁止自动重定向

HttpClient4.3中默认允许自动重定向,导致程序中不能跟踪跳转情况,其实只需要在RequestConfig中setRedirectsEnabled(false)即可(默认是true):

private RequestConfig createConfig(int timeout, boolean redirectsEnabled)

{

    retun RequestConfig.custom()

        .setSocketTimeout(timeout)

        .setConnectTimeout(timeout)

        .setConnectionRequestTimeout(timeout)

        .setRedirectsEnabled(redirectsEnabled)

        .build();

}

public void test(String url)

{

  CloseableHttpClient client = HttpClients.createDefault();   

    try  

    {    

        HttpGet httpGet = new HttpGet(url);    

        httpGet.setConfig(createConfig(5000, false));    

        CloseableHttpResponse response = client.execute(httpGet);    

        try    

        {      

            Header h = response.getFirstHeader("Location");      

            if(h!=null)      

            {         

                System.out.println("重定向地址:"+h.getValue());      

            }    

        }    

        finally    

        {      

            response.close();    

        }  

    }  

    finally  

    {  

      client.close();  

    }

}

 

另外如发生重定向,response的状态码为302,不是200。

你可能感兴趣的:(httpclient)