HttpClient4.4.1模擬登陸知乎

HttpClient4.4.1模擬登陸知乎

一,登陸要Post的表單數據是什麼

這部分能夠使用Wireshark工具來抓包就能夠了,發現須要如下數據:java

"_xsrf" = xxxx(這是一個變更的數據,須要先活取獲取知乎首頁源碼來得到)
"email" = 郵箱
"password" = 密碼
"rememberme" = "y"(或者n也能夠)cookie

  • 獲取_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策略,post

RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();//標準Cookie策略
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();//設置進去
相關文章
相關標籤/搜索