在 android 中存储 Http cookie

我使用授权给网站开发一个Android客户端。示例代码如下:

public void run() {
    handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
    httpClient = new DefaultHttpClient();
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    HttpResponse response = null;
    try{            
        switch (method){
        case POST:
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeaders(headers);
            if (data != null) httpPost.setEntity(new StringEntity(data));
            response = httpClient.execute(httpPost);
            break;
        }
        processEntity(response);

    }catch(Exception e){
        handler.sendMessage(Message.obtain(handler, HttpConnection.DID_ERROR, e));

    }
    ConnectionManager.getInstanse().didComplete(this);      
}

如何保存 cookies?

你可以从HttpResponse response中获取 cookies

String mCookies[] = response.getHeaders("cookie");

将它们添加到你的下一个请求:

HttpClient httpClient = new DefaultHttpClient();

//parse name/value from mCookies[0]. If you have more than one cookie, a for cycle is needed.
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("name", "value");
cookieStore.addCookie(cookie);

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

HttpGet httpGet = new HttpGet("http://www.domain.com/"); 

HttpResponse response = httpClient.execute(httpGet, localContext);

我是这么做的:
1.服务器设置cookie;
2.客户端从服务器获取cookie并保存;
3.客户端页面跳转是判断url是否包含服务器地址,如果包含则读取cookie

具体是通过SharedPreferences来实现保存和读取的

保存:

SharedPreferences sp = context.getSharedPreferences(Const.eBag,
                        Context.MODE_PRIVATE);

                sp.edit()
                        .putString(account + "_ticket",
                                data.getString("ticket"))
                        .putString(account + "_ID", data.getString("id"))
                        .putString(account + "_AccountID", account)
                        .putString(account + "_DisplayName",
                                data.getString("display")).commit();

读取:

String ticket = context.getSharedPreferences(Const.eBag, Context.MODE_PRIVATE).getString(Const.username + "@" + Const.domain + "_ticket", null);
            String cookieStr = context.getResources().getString(R.string.cookie_name) + "=" + "_wsut_=" + ticket + ";" + "Domain=" + context.getResources().getString(R.string.DOMAIN) + ";" + "PATH=" + context.getResources().getString(R.string.PATH) + ";" + "EXPIRES=" + context.getResources().getString(R.string.EXPIRES);
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Cookie", cookieStr);
            webView.loadUrl(tag, headers);