使用HttpClient來模擬浏覽器登錄網站,然後可以進行操作,比如發布信息等
第一步:獲取實際的post網址,(不考慮復雜情況下)
1、需要使用到firefox的httpfox插件,httpfox中clear一下,然後start開始捕獲
2、切換回網頁的登錄頁面,開始輸入自己的賬號密碼登錄,登錄成功後切回httpfox中stop,查看最近的post方法中包含的Post Data數據,和此post方法的url網址,
3、這樣就得到了模擬登錄時需要Post的數據參數(Parameter)和值(Value),以及實際Post的網址URL
第二步,使用HttpClient來登錄
1、簡單核心代碼如下
1 CloseableHttpClient httpclient = HttpClients.createDefault();
2 List<NameValuePair> postData = new ArrayList<NameValuePair>();
3 //這裡可能有多個參數
4 postData.add(new BasicNameValuePair("username", "username"));
5 postData.add(new BasicNameValuePair("password", "password"));
6 //URL是實際的post地址,使用httpFox得到
7 HttpPost httppost = new HttpPost(URL); 9 try {11 httppost.setEntity(new UrlEncodedFormEntity(postData, "GBK"));
12 response = httpclient.execute(httppost);
15 } catch (IOException e) {
16 } finally {
17 closeIO(response);
18 }