`

(原创) HttpComponents 重定向问题分析和解决

阅读更多

HttpComponents 重定向问题分析和解决

 

一、 起因:

最近在学习使用HttpComponents登陆网站,这样的登陆毫无疑问使用的是post方法提交。

但是在登录的过程中,有的会返回302状态代码。这是因为该网站使用了重定向链接造成的。

于是开始了漫长的查阅资料的过程。

 

二、 过程:

国内关于HttpComponents处理302状态问题的例子不多,基本上都是一些简单的例子或者API的翻译。

后来去google搜索,才解决了问题。

 

三、 解决方法:

 

1. 原因所在:

httpcomponents 在处理重定向问题时,默认的情况下是有限制的:

对于 HEAD 和 GET 方法, HttpComponents 会自动做重定向处理;

对于 POST 和 PUT 方法, HttpComponents 不会进行自动重定向处理,这需要用户自己设定才行。

 

下面是 DefaultRedirectStrategy 中的描述:

Default implementation of RedirectStrategy. This strategy honors the restrictions on automatic redirection of entity enclosing methods such as POST and PUT imposed by the HTTP specification. 302 Moved Temporarily, 301 Moved Permanently and 307 Temporary Redirect status codes will result in an automatic redirect of HEAD and GET methods only. POST and PUT methods will not be automatically redirected as requiring user confirmation.

The restriction on automatic redirection of POST methods can be relaxed by using LaxRedirectStrategy instead of DefaultRedirectStrategy.

 

在这段描述中可以知道, 想要使 POST 和 PUT 方法可以自动处理重定向链接,使用 LaxRedirectStrategy 类即可。

 

2. 代码的用法:

 

DefaultHttpClient client = new DefaultHttpClient();
LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
// 设定自己需要的重定向策略
client.setRedirectStrategy(redirectStrategy);
		
// 创建登陆form
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", USERNAME));
formparams.add(new BasicNameValuePair("password", PASSWORD));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
		
// 创建登陆请求
HttpPost loginPost = new HttpPost(URL_LOGIN);
loginPost.setEntity(formEntity);
		
// 执行请求, 
// 在使用默认的重定向策略是,状态代码返回的是 302
// 使用了重定向策略后, 状态代码返回的是 200
HttpResponse loginResponse = client.execute(loginPost);
System.out.println("登录请求放回状态代码: " + loginResponse.getStatusLine().getStatusCode());
 
至此,使用 HttpComponents 发送POST方法, 返回302重定向的问题就解决了。
PS: HttpComponents 的API写的比较简单, 如果有谁使用这个项目的话,能把自己遇到的问题写下了就更好了,在大家共同的努力下,我们会少走很多弯路,节约更多时间学习。
 
3. 下面提供两个链接,有兴趣的可以看看
帮我解决此问题的的连接:
还有一篇老外自己写的重定向类:
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics