最近在做一个网站的爬虫程序,使用HTTPURLConnection 打开连接,提交 post请求,但是,返回的 HTTP 代码总是 302。
设置重定向:
HttpURLConnection.setFollowRedirects(true);
返回了:
HttpURLConnection.HTTP_OK
但是,下载的网页源代码提示:页面超时,网页被重定向到主页了。
在网上找了找,发现 HttpURLConnection不能维护 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<String, List<String>> maps = hc.getHeaderFields(); List<String> coolist = maps.get(cookieskey); Iterator<String> 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);
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<URI> uris = store.getURIs(); for (URI ur : uris) { // 筛选需要的 URI // 得到属于这个 URI 的所有 Cookie List<HttpCookie> cookies = store.get(ur); for (HttpCookie coo : cookies) { res = coo; } } return res; }
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
HttpURLConnection与 CookieManager 实现Post提交请求和Cookie管理,布布扣,bubuko.com
HttpURLConnection与 CookieManager 实现Post提交请求和Cookie管理
原文:http://blog.csdn.net/heyu158/article/details/23342533