1.概述

本快速教程将展示如何配置Apache HttpClient 4以自动遵循POST请求的重定向。

默认情况下,只有自动跟随导致重定向的GET请求。如果POST请求被HTTP 301永久移动302找到 - 则不会自动执行重定向

这由HTTP RFC 2616指定:

如果接收到301状态代码以响应除GET或HEAD以外的请求,则用户代理绝不能自动重定向请求,除非用户可以确认它,因为这可能会改变发出请求的条件。

当然,我们需要改变这种行为并放宽严格的HTTP规范。

首先,我们来检查一下默认行为:

@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状态码

2.在HTTP POST上重定向

2.1。对于HttpClient 4.3和之后

在HttpClient 4.3中,为客户端的创建和配置引入了更高级别的API:

@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现在是一个流利API的起点,其允许在比以前更可读的方式在客户端的完整配置。

2.2。对于HttpClient 4.2

在之前版本的HttpClient(4.2)中,我们可以直接在客户端上配置重定向策略:

@SuppressWarnings("deprecation")
@Test
public void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() 
  throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());
 
    HttpResponse response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

请注意,现在,使用新的LaxRedirectStrategy,HTTP限制被放宽,重定向也通过POST进行 - 从而导致200 OK状态码。

2.3。Pre HttpClient 4.2

在HttpClient 4.2之前,LaxRedirectStrategy类不存在,所以我们需要滚动我们自己的:

@Test
public void givenRedirectingPOST_whenConsumingUrlWhichRedirectsWithPOST_thenRedirected() 
  throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new DefaultRedirectStrategy() {
        /** Redirectable methods. */
        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));
}
 

3.总结

本快速指南说明了如何配置Apache HttpClient 4的任何版本以遵循HTTP POST请求的重定向 - 放宽严格的HTTP标准。

评论区域

评论功能已关闭. 提示:评论功能虽已关闭,关闭之前的评论仍然会展示。