这样做的“正确”方法是实现 CookieHandler:http: //developer.android.com/reference/java/net/CookieHandler.html
最基本的方法是扩展 Application 并将其放在您的应用程序 onCreate() 中:
CookieHandler.setDefault(new CookieManager());
请注意: 这只会实现一个默认的 CookieManger。默认的 CookieManger 将在应用程序的特定会话期间管理所有 HTTP 请求的 cookie。但是,它没有任何方法可以在应用程序的后续使用中保留 cookie。
为此,您需要通过实现 CookieStore 来编写自己的 cookie 管理器:http:
//developer.android.com/reference/java/net/CookieStore.html
这是我在当前位于 Google Play 商店中的应用程序中使用的 CookieStore 实现示例:
package com.touchvision.util;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import com.touchvision.Config;
/*
* This is a custom cookie storage for the application. This
* will store all the cookies to the shared preferences so that it persists
* across application restarts.
*/
public class TvCookieStore implements CookieStore {
private static final String LOGTAG = "TV-TvCookieStore";
/*
* The memory storage of the cookies
*/
private Map<String, Map<String,String>> mapCookies = new HashMap<String, Map<String,String>>();
/*
* The instance of the shared preferences
*/
private final SharedPreferences sharedPrefs;
/*
* @see java.net.CookieStore#add(java.net.URI, java.net.HttpCookie)
*/
public void add(URI uri, HttpCookie cookie) {
String domain = cookie.getDomain();
// Log.i(LOGTAG, "adding ( " + domain +", " + cookie.toString() );
Map<String,String> cookies = mapCookies.get(domain);
if (cookies == null) {
cookies = new HashMap<String, String>();
mapCookies.put(domain, cookies);
}
cookies.put(cookie.getName(), cookie.getValue());
if (cookie.getName().startsWith("SPRING_SECURITY") && !cookie.getValue().equals("")){
// Log.i(LOGTAG, "Saving rememberMeCookie = " + cookie.getValue() );
// Update in Shared Preferences
Editor e = sharedPrefs.edit();
e.putString(Config.PREF_SPRING_SECURITY_COOKIE, cookie.toString());
e.commit(); // save changes
}
}
/*
* Constructor
*
* @param ctxContext the context of the Activity
*/
public TvCookieStore(Context ctxContext) {
// Log.i(LOGTAG, "constructor()");
sharedPrefs = ctxContext.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
}
/*
* @see java.net.CookieStore#get(java.net.URI)
*/
public List<HttpCookie> get(URI uri) {
List<HttpCookie> cookieList = new ArrayList<HttpCookie>();
String domain = uri.getHost();
// Log.i(LOGTAG, "getting ( " + domain +" )" );
Map<String,String> cookies = mapCookies.get(domain);
if (cookies == null) {
cookies = new HashMap<String, String>();
mapCookies.put(domain, cookies);
}
for (Map.Entry<String, String> entry : cookies.entrySet()) {
cookieList.add(new HttpCookie(entry.getKey(), entry.getValue()));
// Log.i(LOGTAG, "returning cookie: " + entry.getKey() + "="+ entry.getValue());
}
return cookieList;
}
/*
* @see java.net.CookieStore#removeAll()
*/
public boolean removeAll() {
// Log.i(LOGTAG, "removeAll()" );
mapCookies.clear();
return true;
}
/*
* @see java.net.CookieStore#getCookies()
*/
public List<HttpCookie> getCookies() {
Log.i(LOGTAG, "getCookies()" );
Set<String> mapKeys = mapCookies.keySet();
List<HttpCookie> result = new ArrayList<HttpCookie>();
for (String key : mapKeys) {
Map<String,String> cookies = mapCookies.get(key);
for (Map.Entry<String, String> entry : cookies.entrySet()) {
result.add(new HttpCookie(entry.getKey(), entry.getValue()));
Log.i(LOGTAG, "returning cookie: " + entry.getKey() + "="+ entry.getValue());
}
}
return result;
}
/*
* @see java.net.CookieStore#getURIs()
*/
public List<URI> getURIs() {
Log.i(LOGTAG, "getURIs()" );
Set<String> keys = mapCookies.keySet();
List<URI> uris = new ArrayList<URI>(keys.size());
for (String key : keys){
URI uri = null;
try {
uri = new URI(key);
} catch (URISyntaxException e) {
e.printStackTrace();
}
uris.add(uri);
}
return uris;
}
/*
* @see java.net.CookieStore#remove(java.net.URI, java.net.HttpCookie)
*/
public boolean remove(URI uri, HttpCookie cookie) {
String domain = cookie.getDomain();
Log.i(LOGTAG, "remove( " + domain +", " + cookie.toString() );
Map<String,String> lstCookies = mapCookies.get(domain);
if (lstCookies == null)
return false;
return lstCookies.remove(cookie.getName()) != null;
}
}
上面的自定义 CookieStore 使用 SharedPreferences 来持久化 cookie。您实现上述类的方式与在应用程序类中实现默认 CookieManager 的方式类似,但该行如下所示:
CookieHandler.setDefault( new CookieManager( new TvCookieStore(this), CookiePolicy.ACCEPT_ALL));
如您所见,我真正关心的唯一 Cookie 是 Spring Security Cookie(我们在服务器端使用 Spring Framework)。您的代码显然会因您的特定需求而有所不同。
另一个快速说明:我无数次尝试做你正在做的事情,并在我的 http 客户端类中处理 cookie 的持久性。只不过是头疼而已。试试这个策略。