這篇文章將教你們怎樣配置Apache HttpClient 4 自動跟隨Post請求的重定向。
默認的狀況下,只有GET請求是自動遵循重定向的。若是一個POST請求返回的狀態是HTTP 301或HTTP 302的話, 是不會自動重定向的。html
這裏是[web link="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3"]HTTP RFC 2616[/weblink]的具體說明: java
If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.web
咱們下面就嘗試下POST的301跳轉: 先來看下默認的POST請求 less
@Test public void givenPostRequest_whenConsumingUrlWhichRedirects_thenNotRedirected() throws ClientProtocolException, IOException { HttpClient instance = HttpClientBuilder.create().build(); HttpResponse response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(301)); }
和你看到的同樣,返回的是301狀態碼。並沒能自動重定向ide
**2.1 4.3以及更高的httplient版本 在HttpClient 4.3 或者更高的版本 的API介紹了建立和配置client:
post
@Test public void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { HttpClient instance = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); HttpResponse response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); }HttpClientBuilder 如今比之前更容易使用。容許client 完整的配置。比起之前,更加具備可讀性;
2.2 httplient 4.2 在4.2這個版本中,咱們能夠直接在client上配置重定向規則: ui
@SuppressWarnings("deprecation") @Test public void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new LaxRedirectStrategy());</p> HttpResponse response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); }
使用 new LaxRedirectStrategy() 讓HTTP 限制放寬。能在post的時候自動跟隨從定向-返回200的請求狀態this
2.3 HttpClient 4.2之前的版本
在HttpClient 4.2之前的版本中,LaxRedirectStrategy 這個類是不存在的,因此咱們須要本身實現一下:
code
@Test public void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() throws ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); client.setRedirectStrategy(new DefaultRedirectStrategy() { /*<em> Redirectable methods. </em>/ private String[] REDIRECT_METHODS = new String[] { HttpGet.METHOD_NAME, HttpPost.METHOD_NAME, HttpHead.METHOD_NAME }; @Override protected boolean isRedirectable(String method) { for (String m : REDIRECT_METHODS) { if (m.equalsIgnoreCase(method)) { return true; } } return false; } }); HttpResponse response = client.execute(new HttpPost("http://t.co/I5YYd9tddw")); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); }
這篇文章說明了怎樣在Apache HttpClient 4 各個不一樣的版本中配置POST的redirects重定向請求。有問題歡迎留言一塊兒討論解決htm