2016-03-14 203 views
2

與java.net.HttpURLConnection相比,Apache HttpClient處理GET請求的方式不同嗎?處理GET請求 - Apache HttpClient vs java.net.HttpURLConnection

我試着向一個URL發出一個GET請求,它使用這兩種方法返回一個重定向。雖然從HttpURLConnection的響應代碼返回一個302預期,使得使用HttpClient的結果在200

下同電話是我的代碼:

// Using Apache HttpClient 
HttpClient client = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); 
HttpGet request = new HttpGet(authUrl); 
HttpResponse response = client.execute(request); 
int responseCode = response.getStatusLine().getStatusCode(); //Returns 200 

// Using java.net.HttpURLConnection 
URL obj = new URL(authUrl); 
HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); 
int responseCode = conn.getResponseCode(); //Returns 302 

這是使用Apache的HttpClient我的第一次,所以我代碼可能是錯誤的。

謝謝。

+0

看標題爲「位置」可以讀取頭 - 你可以從得到重定向。 (for header header:response.getHeaders(「Location」)){redirectLink = header.getValue(); }' – Ascalonian

+0

我試過了。它沒有任何「位置」標題,因爲響應是200,而不是302。 – drunkenfist

回答

0

嘗試關閉自動重定向處理。最有可能的HttpClient會被重定向到302響應指定的位置,如果需要通過重定向鏈走路而HUC出於某種原因不

1

Handling GET requests - Apache HttpClient vs java.net.HttpURLConnection ,您應該設置HttpPost/HTTPGET禁止重定向(HttpRequestBase),用於例如:

public void disableRedirect(HttpRequestBase request) { 
    request.setConfig(RequestConfig.custom().setRedirectsEnabled(false).build()); 
} 

後,你會得到預期與response.getStatusLine().getStatusCode() 302響應代碼和@Ascalonian說