這部分可以使用Wireshark工具來抓包就可以了,發現需要以下數據:
"_xsrf" = xxxx(這是一個變動的數據,需要先活取獲取知乎首頁源碼來獲得)"email" = 郵箱"passWord" = 密碼"rememberme" = "y"(或者n也可以)
獲取_xsrf數據:
String xsrfValue = responseHtml.split("<input type=/"hidden/" name=/"_xsrf/" value=/"")[1].split("/"/>")[0];responseHtml是首頁的源碼,根據網頁的組織形式,把_xsrf數據分割出來。
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build(); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); HttpGet get = new HttpGet("http://www.zhihu.com/"); try { CloseableHttPResponse response = httpClient.execute(get); String responseHtml = EntityUtils.toString(response.getEntity()); String xsrfValue = responseHtml.split("<input type=/"hidden/" name=/"_xsrf/" value=/"")[1].split("/"/>")[0]; System.out.println("xsrfValue:" + xsrfValue); response.close(); List<NameValuePair> valuePairs = new LinkedList<NameValuePair>(); valuePairs.add(new BasicNameValuePair("_xsrf" , xsrfValue)); valuePairs.add(new BasicNameValuePair("email", 郵箱)); valuePairs.add(new BasicNameValuePair("password", 密碼)); valuePairs.add(new BasicNameValuePair("rememberme", "y")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, Consts.UTF_8); HttpPost post = new HttpPost("http://www.zhihu.com/login"); post.setEntity(entity); httpClient.execute(post);//登錄 HttpGet g = new HttpGet("http://www.zhihu.com/question/following"); CloseableHttpResponse r = httpClient.execute(g);//獲取子集關注的問題頁面測試一下是否登陸成功 System.out.println(EntityUtils.toString(r.getEntity())); r.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } }此處要注意開頭的RequestConfig,我一開始是沒有設置cookie這方面的額內容的,結果一直提示有cookie錯誤,所以查看了HttpClient手冊,上面提到了選擇Cookie策略,通過這種方法設置一個全局的Cookie策略,
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();//標準Cookie策略CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();//設置進去新聞熱點
疑難解答