HttpClients 如何自動處理重定向
HttpClient只是模擬一次tcp請求,瀏覽器則會幫你處理重定向、快取等事情。這也就是為什麼用瀏覽器表單post提交後,不管服務端如何重定向,都能正常接收到服務端返回的資料。
但是用HttpClient呢,你會發現,請求後,會返回302,因為POST方式提交HttpClient是不會幫你處理重定向的。
方法一:(自己手動處理)
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost= new HttpPost(http://ip:sport/xxx);
CloseableHttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode=="+statusCode); //返回碼
Header header=response.getFirstHeader("Location");
//重定向地址
String location = header.getValue();
System.out.println(location);
//然後再對新的location發起請求即可
HttpGet httpGet = new HttpGet(location);
CloseableHttpResponse response2 = httpclient.execute(httpGet);
System.out.println("返回報文"+EntityUtils.toString(response2.getEntity(), "UT-F-8"));
方法二:(已有工具類)
HttpClientBuilder builder = HttpClients.custom()
.disableAutomaticRetries() //關閉自動處理重定向
.setRedirectStrategy(new LaxRedirectStrategy());//利用LaxRedirectStrategy處理POST重定向問題
CloseableHttpClient client = builder.build();
HttpPost httpPost= new HttpPost(http://ip:sport/xxx);
CloseableHttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode=="+statusCode); //返回碼
System.out.println("返回報文"+EntityUtils.toString(response.getEntity(), "UT-F-8"));