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

Android WebView 如何帶上登入後的 Cookie

編輯:關於 Android 程式設計

前兩天想做一个「模擬登入」的小功能:先用程式送出帳密完成登入,再用 WebView 打開那些需要登入才能看的頁面。結果不管怎麼載入,一律被踢回登入頁。查了一輪才確認原因——登入階段拿到的 Cookie 沒有交給 WebView。以下記錄可行的做法。

登入階段:把 Cookie 收集起來

private Cookie cookie;
public static HttpContext localContext;
public static List<Cookie> cookies; // 保存下來的 cookie
public String cookieStr;

/**
 * 登入時保存 cookie
 * @param url 登入位址
 * @param data 帳號與密碼
 * @return 回應的 HTML
 */
public String login(String url, String data[]) {
    HttpClient client = null;
    String html = null;
    try {
        client = new DefaultHttpClient();
        // 建立 cookie store 的本地實例
        CookieStore cookieStore = new BasicCookieStore();
        localContext = new BasicHttpContext();
        // 把自訂的 cookie store 綁定到本地內容中
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpPost post = new HttpPost(url);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("username", data[0]));
        parameters.add(new BasicNameValuePair("passwd", data[1]));
        parameters.add(new BasicNameValuePair("login", "登錄"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "utf-8");
        post.setEntity(entity);

        HttpResponse response = client.execute(post, localContext);
        if (response.getStatusLine().getStatusCode() == 200) {
            InputStream content = response.getEntity().getContent();
            BufferedReader buffer = new BufferedReader(
                    new InputStreamReader(content, "gbk"));
            String line = null;
            while ((line = buffer.readLine()) != null) {
                html += line;
            }
            cookies = cookieStore.getCookies();
            System.out.println("cookies.size():" + cookies.size());
            if (!cookies.isEmpty()) {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
            buffer.close();
        } else {
            System.out.println("UtilsLogin:" + response.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
    return html;
}

這裡的關鍵不是 HttpPost 本身,而是那個 BasicCookieStore。預設情況下每次請求都是「無狀態」的,伺服器設的 Cookie 用完即丟。把 CookieStore 綁到 HttpContext 上,並在呼叫 execute 時把這個 context 一起傳進去,回應中的 Set-Cookie 才會被保留下來,最後用 cookieStore.getCookies() 取出。

把 Cookie 灌進 WebView

private WebView wvTempShow;
private String receiveUrl;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_temp_web_view);
    wvTempShow = (WebView) findViewById(R.id.wv_tempShow);
    Intent intent = this.getIntent();
    receiveUrl = intent.getStringExtra("openUrl");

    // 取得 cookie 管理者
    CookieManager cookieManager = CookieManager.getInstance();
    // 把登入時取得的 cookie 拼成字串
    String oldCookie = UtilsLogin.cookies.get(0).getName() + "=" + UtilsLogin.cookies.get(0).getValue() + ";"
            + UtilsLogin.cookies.get(1).getName() + "=" + UtilsLogin.cookies.get(1).getValue() + ";";
    System.out.println("oldCookie:" + oldCookie);

    cookieManager.setCookie(receiveUrl, oldCookie);
    wvTempShow.getSettings().setDefaultTextEncodingName("gbk");
    wvTempShow.loadUrl(receiveUrl);
    wvTempShow.setWebViewClient(new MyWebViewClient());
}

class MyWebViewClient extends WebViewClient {
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
    }
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
    }
}

WebView 與 Apache HttpClient 是兩套獨立的網路堆疊,Cookie 不會自動共享。CookieManager 就是官方留給我們的橋樑:先用 getInstance() 取到單例,再用 setCookie(url, cookieString) 把字串塞進去,之後 WebView 發出的請求就會自動帶上。

不確定該帶哪些 Cookie 怎麼辦

可以先反查 WebView 手上已經有什麼:

CookieManager cookieManager = CookieManager.getInstance();
String cookieStr = cookieManager.getCookie("https://example.com/page.asp");
System.out.println("CookieStr = " + cookieStr);

把結果印出來,照著同樣的 name=value 格式自己拼好,再交給 setCookie()。

幾個容易踩到的細節

第一,上面的範例是硬寫索引取前兩個 Cookie,實務上應該改成迴圈遍歷,用 StringBuilder 拼接並在每項之間加分號,否則伺服器一多發幾個 Cookie 就會漏帶或陣列越界。

第二,setCookie 的第一個參數是 URL,Cookie 的作用域與路徑相關,如果登入網域與要開啟的頁面網域不同,可能需要對多個網域分別設定,或者改用 setAcceptCookie 搭配全域設定。

第三,Cookie 是有時效的。若登入回應裡的過期時間已過,WebView 一樣會被踢回登入頁,這時候要檢查的是時效而不是設定方式。

第四,從 Android 5.0 起 WebView 的 Cookie 需要手動同步落地。呼叫 CookieManager.getInstance().flush() 可把記憶體中的 Cookie 寫入永久儲存,避免應用被回收後登入狀態遺失。

最後提醒一句:以程式送出帳密完成登入,本質上是模擬表單提交,欄位名稱、編碼(範例中的 gbk)與隱藏欄位都得和目標網站一致,否則伺服器會當成登入失敗處理,Cookie 自然也不會發下來。

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