最近在做一个网站的爬虫程序,使用HTTPURLConnection 打开连接,提交 post请求,但是,返回的 HTTP 代码总是 302。
设置重定向:
HttpURLConnection.setFollowRedirects(true);
返回了:
HttpURLConnection.HTTP_OK
但是,下载的网页源代码提示:页面超时,网页被重定向到主页了。
在网上找了找,发现 HttpURLConnection不能维护 Cookie.
好,那我就自己维护 Cookie。
网上有这么两种方法:
1. 通过 获取 头信息的方式获取 cookie ,然后再将获取的 cookie 写入下一个请求。代码如下:
HttpURLConnection.setFollowRedirects(true);
hc = (HttpURLConnection) url.openConnection();
hc.setRequestMethod("POST");
hc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
hc.setDoOutput(true);
hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
hc.setRequestProperty("Content-Language", "zh-cn");
hc.setRequestProperty("Connection", "keep-alive");
hc.setRequestProperty("Cache-Control", "no-cache");
if (code == HttpURLConnection.HTTP_OK) {
String cookieskey = "Set-Cookie";
Map> maps = hc.getHeaderFields();
List coolist = maps.get(cookieskey);
Iterator it = coolist.iterator();
StringBuffer sbu = new StringBuffer();
sbu.append("eos_style_cookie=default; ");
while(it.hasNext()){
sbu.append(it.next());
}
System.out.println(sbu.toString());
return sbu.toString();
}//if
然后,我把获取的cookie 写入请求,再次提交请求:
//省略了其它部分
hc.setRequestProperty("Cookie",MHttpConnect.cookie);
测试,仍然不可以。
2.下面,继续搜索互联网,网上说可以通过CookieManager 实现 对Cookie的管理。
public static void storecoo(URI uri,String strcoo) {
// 创建一个默认的 CookieManager
// 将规则改掉,接受所有的 Cookie
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
// 保存这个定制的 CookieManager
CookieHandler.setDefault(manager);
// 接受 HTTP 请求的时候,得到和保存新的 Cookie
HttpCookie cookie = new HttpCookie("Cookie: ", strcoo);
//cookie.setMaxAge(60000);//没这个也行。
manager.getCookieStore().add(uri, cookie);
}
public static HttpCookie getcookies(){
HttpCookie res = null;
// 使用 Cookie 的时候:
// 取出 CookieStore
CookieStore store = manager.getCookieStore();
// 得到所有的 URI
List uris = store.getURIs();
for (URI ur : uris) {
// 筛选需要的 URI
// 得到属于这个 URI 的所有 Cookie
List cookies = store.get(ur);
for (HttpCookie coo : cookies) {
res = coo;
}
}
return res;
}
然后,再将cookie 写入请求就可以了。
if (MHttpConnect.cookie == null) {
TestConnect tc = new TestConnect();
try {
uri = new URI("http://rexian.beijing.gov.cn/");
} catch (URISyntaxException e) {
e.printStackTrace();
}
MyCookiesDemo.storecoo(uri, tc.test());
HttpCookie hcoo = MyCookiesDemo.getcookies();
if(!hcoo.hasExpired()){
MHttpConnect.cookie = hcoo.getValue();
}
//MHttpConnect.cookie = tc.test();//直接注入cookie不可以。
}
经过测试,可以爬取网页内容。
下面是我的疑问,为什么直接注入cookie 不可以?
爬取的网址:
http://rexian.beijing.gov.cn/index.jsp?agMode=1
例子程序:
链接:http://pan.baidu.com/s/1i3ou4Od 密码:4g7a
你如果要运行的话,可以直接导入Eclipse,运行下面这个类:
/SpiderBeiJing/src/com/bistu/spider/TestConnect.java