Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 HttpClient 自動登入 Discuz 論壇的完整拆解

編輯:關於 Android 程式設計

想用程式自動登入論壇,第一步不是寫程式,而是先搞清楚瀏覽器到底做了什麼。

一、觀察瀏覽器的行為

用 Firefox 打開 Hi-PDA 的登入頁,輸入帳號密碼按下登入,接著透過 Firebug 觀察/

可以看到瀏覽器向 https://www.hi-pda.com/forum/logging.php?action=login&loginsubmit=yes&inajax=1 發了一個 POST 請求。

二、七個參數各自是什麼

  1. cookietime = 259200:固定值,照傳即可。
  2. formhash:Discuz 的防 CSRF 隨機碼,值藏在當前頁面原始碼中。搜尋頁面源碼裡的 formhash,會發現和請求中的值一致。
  3. loginfield = username:固定值。
  4. password:你輸入的密碼。
  5. questionid = 0:安全提問的編號,沒設過安全提問就是 0。
  6. referer:來源頁網址,直接填論壇首頁。
  7. username:你的帳號。

關鍵在於 formhash 是動態的,所以程式必須先抓一次頁面把它解析出來。

三、抓取 formhash

用 HttpClient 發 GET 取得登入頁原始碼,再交給 Jsoup 用 CSS 選擇器取出 value:

HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("https://www.hi-pda.com/forum/logging.php?action=login");
try {
    HttpResponse httpResponse = httpClient.execute(httpGet);
    HttpEntity httpEntity = httpResponse.getEntity();
    String s = EntityUtils.toString(httpEntity, "GBK");
    Element formhash_Element = Jsoup.parse(s).select("input[name=formhash]").first();
    formhash = formhash_Element.attr("value");
    System.out.println(formhash);
} catch (Exception e) { }

注意編碼要用 GBK,這類老論壇鮮少走 UTF-8。

四、送出登入請求

HttpPost httpPost = new HttpPost(
    "https://www.hi-pda.com/forum/logging.php?action=login&loginsubmit=yes&inajax=1");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("formhash", formhash));
params.add(new BasicNameValuePair("loginfield", "username"));
params.add(new BasicNameValuePair("password", "******"));
params.add(new BasicNameValuePair("questionid", "0"));
params.add(new BasicNameValuePair("referer", "https://www.hi-pda.com/forum/index.php"));
params.add(new BasicNameValuePair("username", "******"));
try {
    httpPost.setEntity(new UrlEncodedFormEntity(params, "GBK"));
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String ans = EntityUtils.toString(entity);
} catch (Exception e) { }

五、維持登入狀態

重點是:後續請求必須沿用同一個 HttpClient 物件,Cookie 才會被自動帶上。驗證方式很簡單,拿這個 client 去抓需要登入才能看的版面:

HttpGet getHome = new HttpGet("https://www.hi-pda.com/forum/index.php");
try { httpClient.execute(getHome); } catch (Exception e) { }

HttpGet getD = new HttpGet("https://www.hi-pda.com/forum/forumdisplay.php?fid=2");
try {
    HttpResponse responseD = httpClient.execute(getD);
    HttpEntity entityD = responseD.getEntity();
    String str = EntityUtils.toString(entityD, "GBK");
    System.out.println(str);
} catch (Exception e) { }

輸出的內容顯示的是已登入狀態下的 D 版,登入流程就此打通。整套路心得來不複雜:先模擬 GET 取 token,再 POST 送出憑證,最後靠 client 物件本身維護 session。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved