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。