DIV CSS 佈局教程網

HttpClient 模擬登入的實作:用 Cookie 換到一個已登入的用戶端
編輯:JavaScript綜合知識     

有些站點的登入流程帶著一堆加密與驗證碼,硬刻登入表單成本很高。實務上更快的做法是:先在瀏覽器正常登入,把 cookie 取出來餵給 HttpClient。本文記錄這條路徑。

第一步:取得登入後的 cookie

最省事的方式是讓伺服器端輸出一段會寫 cookie 的頁面,用瀏覽器開一次即可:

<html>
<meta http-equiv='Content-Type' content='text/html; charset=gb2312'>
<script>document.cookie='utmpnum=51;path=/;domain=.' + window.location.host</script>
<script>document.cookie='utmpkey=20154732;path=/;domain=.' + window.location.host</script>
<script>document.cookie='utmpuserid=yay;path=/;domain=.' + window.location.host</script>
<meta http-equiv='Refresh' content='0; url=/firstpage.php'>
</html>

這裡刻意把 domain 設成 window.location.host,讓 cookie 自動綁到目前網域,不必寫死。

第二步:HttpClient 4.3 的寫法

最簡單的方式是組一個 BasicCookieStore,把 cookie 逐筆塞進去,再交給 HttpClient:

CookieStore cookieStore = new BasicCookieStore();

for (int i = 0; i < 3; i++) {
    String name, value;
    int flag = s.indexOf("document.cookie");
    s = s.substring(flag + 17);
    flag = s.indexOf('=');
    name  = s.substring(0, flag);
    value = s.substring(flag + 1, s.indexOf(';'));

    BasicClientCookie cookie = new BasicClientCookie(name, value);
    cookie.setVersion(0);
    cookie.setDomain(".www.zju88.org");   // 對應 window.location.host 的返回值
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
}

// 把 store 掛上去
CloseableHttpClient httpclient = HttpClients.custom()
        .setDefaultCookieStore(cookieStore)
        .build();

之後用這個 httpclient 發出的所有請求,都會自動帶上這些 cookie,看起來就跟已登入的使用者無異。

Android 上的替代做法

Android 的 HttpClient API 沒有完全對應的介面,實務上比較乾脆的方式是每次請求前手動加 header:

String cookie = "";
for (int i = 0; i < 3; i++) {
    String name, value;
    int flag = s.indexOf("document.cookie");
    s = s.substring(flag + 17);
    flag = s.indexOf('=');
    name  = s.substring(0, flag);
    value = s.substring(flag + 1, s.indexOf(';'));
    cookie += name + "=" + value;
    if (i != 2) cookie += ";";
}

HttpGet httpget = new HttpGet(url);
httpget.addHeader("Cookie", cookie);
HttpResponse response = httpclient.execute(httpget);

若 HttpClient 裡已經有 cookie,可能還需要調整 cookie policy,這部分建議直接查官方 API 文件。

這條路徑的限制

用 cookie 拼接的做法在 session 有效期內很好用,但資料是明文可讀的,不要把真實憑證寫進原始碼或提交進版本控制。另外這種字串切片的解析方式很脆弱,cookie 數量一變就得改迴圈次數;正式專案建議用既有的 cookie 解析工具,並把憑證改由環境變數或設定檔注入。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved