HttpClient4.0手动处理redirect

    上个星期做了一个爬虫,主要是实现手机上不通过标准浏览器的方式实现facebook认证过程,期间遇到个问题需要手动处理redirect。
httpclient4.0的get方法完全redirect,post方法部分支持redirect,也就是说,我们在大部分情况下爬网页时中间的一些redirect过程可以当作是透明的,输入一个url得到的是redirect后的最终结果页。
刚好,我需要redirect过程中的一个临时页面的一些信息,而httpclient4.0 "自作主张"地帮我忽略了,如何手动处理呢?
结过查看其内部源码,httpclient默认是通过defaultredirecthandler来管理跳转的,该类继承自接口,该接口有两个方法

public uri getlocationuri(httpresponse response, httpcontext context)
throws protocolexception;
public boolean isredirectrequested(httpresponse response,
httpcontext context);

其中isredirectrequested是用于判断当前的请求是否需要redirect。我们只需要定义一个自己的redirecthandler来处理redirect就可以了,如下:
public class dummyredirecthandler implements redirecthandler {

public uri getlocationuri(httpresponse response, httpcontext context)
throws protocolexception {
// todo auto-generated method stub
return null;
}

public boolean isredirectrequested(httpresponse response,
httpcontext context) {
// 由于我们需要手动处理所有的redirect,所以直接return false
return false;
}

}

abstracthttpclient类setredirecthandler方法用于设置自定义redirecthandler实现

httpclient.setredirecthandler(new dummyredirecthandler());

然后通过搬运捕获header("location"),可以取得跳转中间过程的url,希望能帮到像我这样做爬虫天天在网上的童鞋。  

你可能感兴趣的:(java,工作)