在 Android 上使用 okhttp 2 的持久 Cookie 存储
Posted
技术标签:
【中文标题】在 Android 上使用 okhttp 2 的持久 Cookie 存储【英文标题】:Persistent Cookie store using okhttp 2 on Android 【发布时间】:2014-10-17 04:19:07 【问题描述】:在我的 android 应用程序中,我试图从 android-async-http
切换到支持异步网络和版本 2.0 的 okhttp
。虽然前者附带了 persistent cookie storage 的实现,但我不知道如何为 okhttp
实现类似的东西。
在我的应用程序中,我有一个登录例程,在此期间发送get
请求,如果成功,应该设置一个cookie。此 cookie 应附加到所有后续网络请求,并且应在应用程序重新启动后继续存在。
我在 SO 上找到了the following answer,表明以下代码如果在应用程序的某处执行,将激活持久 cookie 管理,okhttp
将使用它:
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
但是,对我来说它不起作用。 CookieManager
是正确的方法吗?我如何监控设置和存储了哪些 cookie 以进一步调试问题?
【问题讨论】:
【参考方案1】:将代码放入自定义Application
的onCreate
函数可以解决问题。现在可以使用了。
public class MyApplication extends Application
public void onCreate()
super.onCreate();
// enable cookies
java.net.CookieManager cookieManager = new java.net.CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
我设法通过okhttp
获得了持久性cookie,下面的CookieStore
部分复制自android-async-http
之一。它适用于 API lvl 9 并且可能更少。
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import java.io.*;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* A persistent cookie store which implements the Apache HttpClient CookieStore interface.
* Cookies are stored and will persist on the user's device between application sessions since they
* are serialized and stored in SharedPreferences. Instances of this class are
* designed to be used with AsyncHttpClient#setCookieStore, but can also be used with a
* regular old apache HttpClient/HttpContext if you prefer.
*/
public class PersistentCookieStore implements CookieStore
private static final String LOG_TAG = "PersistentCookieStore";
private static final String COOKIE_PREFS = "CookiePrefsFile";
private static final String COOKIE_NAME_PREFIX = "cookie_";
private final HashMap<String, ConcurrentHashMap<String, HttpCookie>> cookies;
private final SharedPreferences cookiePrefs;
/**
* Construct a persistent cookie store.
*
* @param context Context to attach cookie store to
*/
public PersistentCookieStore(Context context)
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new HashMap<String, ConcurrentHashMap<String, HttpCookie>>();
// Load any previously stored cookies into the store
Map<String, ?> prefsMap = cookiePrefs.getAll();
for(Map.Entry<String, ?> entry : prefsMap.entrySet())
if (((String)entry.getValue()) != null && !((String)entry.getValue()).startsWith(COOKIE_NAME_PREFIX))
String[] cookieNames = TextUtils.split((String)entry.getValue(), ",");
for (String name : cookieNames)
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null)
HttpCookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null)
if(!cookies.containsKey(entry.getKey()))
cookies.put(entry.getKey(), new ConcurrentHashMap<String, HttpCookie>());
cookies.get(entry.getKey()).put(name, decodedCookie);
@Override
public void add(URI uri, HttpCookie cookie)
String name = getCookieToken(uri, cookie);
// Save cookie into local store, or remove if expired
if (!cookie.hasExpired())
if(!cookies.containsKey(uri.getHost()))
cookies.put(uri.getHost(), new ConcurrentHashMap<String, HttpCookie>());
cookies.get(uri.getHost()).put(name, cookie);
else
if(cookies.containsKey(uri.toString()))
cookies.get(uri.getHost()).remove(name);
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableHttpCookie(cookie)));
prefsWriter.commit();
protected String getCookieToken(URI uri, HttpCookie cookie)
return cookie.getName() + cookie.getDomain();
@Override
public List<HttpCookie> get(URI uri)
ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
if(cookies.containsKey(uri.getHost()))
ret.addAll(cookies.get(uri.getHost()).values());
return ret;
@Override
public boolean removeAll()
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.clear();
prefsWriter.commit();
cookies.clear();
return true;
@Override
public boolean remove(URI uri, HttpCookie cookie)
String name = getCookieToken(uri, cookie);
if(cookies.containsKey(uri.getHost()) && cookies.get(uri.getHost()).containsKey(name))
cookies.get(uri.getHost()).remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
if(cookiePrefs.contains(COOKIE_NAME_PREFIX + name))
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
prefsWriter.putString(uri.getHost(), TextUtils.join(",", cookies.get(uri.getHost()).keySet()));
prefsWriter.commit();
return true;
else
return false;
@Override
public List<HttpCookie> getCookies()
ArrayList<HttpCookie> ret = new ArrayList<HttpCookie>();
for (String key : cookies.keySet())
ret.addAll(cookies.get(key).values());
return ret;
@Override
public List<URI> getURIs()
ArrayList<URI> ret = new ArrayList<URI>();
for (String key : cookies.keySet())
try
ret.add(new URI(key));
catch (URISyntaxException e)
e.printStackTrace();
return ret;
/**
* Serializes Cookie object into String
*
* @param cookie cookie to be encoded, can be null
* @return cookie encoded as String
*/
protected String encodeCookie(SerializableHttpCookie cookie)
if (cookie == null)
return null;
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
ObjectOutputStream outputStream = new ObjectOutputStream(os);
outputStream.writeObject(cookie);
catch (IOException e)
Log.d(LOG_TAG, "IOException in encodeCookie", e);
return null;
return byteArrayToHexString(os.toByteArray());
/**
* Returns cookie decoded from cookie string
*
* @param cookieString string of cookie as returned from http request
* @return decoded cookie or null if exception occured
*/
protected HttpCookie decodeCookie(String cookieString)
byte[] bytes = hexStringToByteArray(cookieString);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
HttpCookie cookie = null;
try
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
cookie = ((SerializableHttpCookie) objectInputStream.readObject()).getCookie();
catch (IOException e)
Log.d(LOG_TAG, "IOException in decodeCookie", e);
catch (ClassNotFoundException e)
Log.d(LOG_TAG, "ClassNotFoundException in decodeCookie", e);
return cookie;
/**
* Using some super basic byte array <-> hex conversions so we don't have to rely on any
* large Base64 libraries. Can be overridden if you like!
*
* @param bytes byte array to be converted
* @return string containing hex values
*/
protected String byteArrayToHexString(byte[] bytes)
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte element : bytes)
int v = element & 0xff;
if (v < 16)
sb.append('0');
sb.append(Integer.toHexString(v));
return sb.toString().toUpperCase(Locale.US);
/**
* Converts hex values from strings to byte arra
*
* @param hexString string of hex-encoded values
* @return decoded byte array
*/
protected byte[] hexStringToByteArray(String hexString)
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2)
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
return data;
SerializableHttpCookie.java
:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.HttpCookie;
public class SerializableHttpCookie implements Serializable
private static final long serialVersionUID = 6374381323722046732L;
private transient final HttpCookie cookie;
private transient HttpCookie clientCookie;
public SerializableHttpCookie(HttpCookie cookie)
this.cookie = cookie;
public HttpCookie getCookie()
HttpCookie bestCookie = cookie;
if (clientCookie != null)
bestCookie = clientCookie;
return bestCookie;
private void writeObject(ObjectOutputStream out) throws IOException
out.writeObject(cookie.getName());
out.writeObject(cookie.getValue());
out.writeObject(cookie.getComment());
out.writeObject(cookie.getCommentURL());
out.writeObject(cookie.getDomain());
out.writeLong(cookie.getMaxAge());
out.writeObject(cookie.getPath());
out.writeObject(cookie.getPortlist());
out.writeInt(cookie.getVersion());
out.writeBoolean(cookie.getSecure());
out.writeBoolean(cookie.getDiscard());
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
String name = (String) in.readObject();
String value = (String) in.readObject();
clientCookie = new HttpCookie(name, value);
clientCookie.setComment((String) in.readObject());
clientCookie.setCommentURL((String) in.readObject());
clientCookie.setDomain((String) in.readObject());
clientCookie.setMaxAge(in.readLong());
clientCookie.setPath((String) in.readObject());
clientCookie.setPortlist((String) in.readObject());
clientCookie.setVersion(in.readInt());
clientCookie.setSecure(in.readBoolean());
clientCookie.setDiscard(in.readBoolean());
【讨论】:
虽然此代码可能有效...您是否考虑过用户是否希望允许所有 cookie 被接受并允许他们对此进行控制?! 请记住,此解决方案将无法在应用程序重新启动后继续存在。这是一个答案,其中包含一些基本代码以保留在 SharedPreferences 中,***.com/questions/12349266/… @ErstwhileIII:是的,用户知道这一点并希望保持登录到我的服务。当然,他们可以随时手动注销。 @Miguel Lavigne:由于某种原因,它现在停止工作,但我会查看您的链接。谢谢! 很好的答案,但基于此答案 (***.com/a/1063760/980387),如果 cookie 的域和路径属性可用,则不应使用 URI。同样在 SerializedCookie 中,HttpCookie httpOnly 属性没有被序列化(它没有访问器也没有修改器)。我准备了一个可以解决这两个问题的答案 (***.com/a/27161496/980387)。【参考方案2】:您可以使用以下代码在 OkHttp 客户端中设置您的 CookieStore:
OkHttpClient client = new OkHttpClient();
client.setCookieHandler(new CookieManager(
new PersistentCookieStore(getApplicationContext()),
CookiePolicy.ACCEPT_ALL));
我做了一个gist with my implementation of a persistent CookieStore 试图在两点上改进janoliver's answer:
-
基于this answer,如果 cookie 的域和路径属性可用,则不应使用 URI。
在 SerializableHttpCookie 类中,HttpCookie httpOnly 属性没有被序列化(它没有访问器也没有修改器)。我的解决方案是使用反射来访问这个私有属性。
【讨论】:
只是一个关于 OkHttpClient 使用的问题。对于每个请求,它应该是持久的(静态的)还是应该为每个请求创建一个新的? @StErMi 您应该对所有请求使用相同的实例。查看 Jakes Wharton 对此帖子的回复 (plus.google.com/118239425803358296962/posts/5nzAvPaitHu) 这是一个比公认答案更干净的解决方案。我将它与 Retrofit 一起使用,效果很好。 Proguard 和反射不能很好地混合,所以添加 '-keep public class package.SerializableHttpCookie *; ' 对你的 proguard 配置有帮助。 对于 okhttp3,请参阅:***.com/questions/34881775/…以上是关于在 Android 上使用 okhttp 2 的持久 Cookie 存储的主要内容,如果未能解决你的问题,请参考以下文章