问题背景:POST请求返回302,导致获取不了数据。
HttpClient instance = HttpClientBuilder.create().build();
HttpResponse response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
- HttpClient 4.3以后的版本
HttpClient instance =
HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
HttpResponse response = instance.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- HttpClient 4.2版本
DefaultHttpClient client = new DefaultHttpClient();
client.setRedirectStrategy(new LaxRedirectStrategy());
HttpResponse response = client.execute(new HttpPost("http://t.co/I5YYd9tddw"));
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
- HttpClient 4.2之前的版本
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));
本人使用的是4.4版本,方法1亲测有效。网上比较多的是方法3的版本,还有的说是获取302返回的location再去请求,太麻烦了。
如果大家试了满意的留言哈,大家一起分享。