Android上使用okhttp 2的持久Cookie存储
在我的Android应用程序中,我正在尝试从Android上使用okhttp 2的持久Cookie存储,android,cookies,okhttp,Android,Cookies,Okhttp,在我的Android应用程序中,我正在尝试从Android异步http切换到okhttp,它支持异步网络sind 2.0版。虽然前者附带了a的实现,但我不知道如何为okhttp实现类似的东西 在我的应用程序中,我有一个登录例程,在此过程中发送一个get请求,如果成功,应该设置一个cookie。此cookie应附加到所有后续网络请求中,并应在应用程序重新启动后继续存在 我发现是这样的,这表明如果在应用程序的某个地方执行以下代码,就会激活持久cookie管理,并且okhttp会使用它: Cookie
Android异步http
切换到okhttp
,它支持异步网络sind 2.0版。虽然前者附带了a的实现,但我不知道如何为okhttp
实现类似的东西
在我的应用程序中,我有一个登录例程,在此过程中发送一个get
请求,如果成功,应该设置一个cookie。此cookie应附加到所有后续网络请求中,并应在应用程序重新启动后继续存在
我发现是这样的,这表明如果在应用程序的某个地方执行以下代码,就会激活持久cookie管理,并且okhttp
会使用它:
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
然而,对我来说,它不起作用。
CookieManager
是正确的方法吗?如何监控设置和存储了哪些cookie以进一步调试问题?将代码放入自定义应用程序的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
和以下CookieStore
获得了持久cookie,这部分是从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;
}
}
您可以使用以下代码在OkHttp客户端中设置CookieStore:
OkHttpClient client = new OkHttpClient();
client.setCookieHandler(new CookieManager(
new PersistentCookieStore(getApplicationContext()),
CookiePolicy.ACCEPT_ALL));
我尝试在两点上改进:
如果cookie的域和路径属性可用,则不应使用基于URI的
在SerializableHttpCookie类中,HttpCookie httpOnly属性未序列化(它既没有访问器也没有变异器)。我的解决方案是使用反射来访问这个私有属性
虽然这个代码可以工作。。。您是否考虑过用户是否希望接受所有cookie,并允许他们控制该cookie?!请记住,此解决方案无法在应用程序重新启动后继续使用。下面是一个答案,其中包含一些基本代码,可以在SharedReferences中持久存在,@erstwhileii:是的,用户知道这一点,并希望继续登录到我的服务中。当然,他们可以随时手动注销。@Miguel Lavigne:出于某种原因,它现在停止工作了,但我会查看您的链接。非常感谢。很好的答案,但是基于这个答案()如果cookies的域和路径属性可用,就不应该使用URI。此外,在SerializedCookie中,HttpCookie httpOnly属性未序列化(它没有访问器或变异器)。我准备了一个答案()来解决这两个问题。只是一个关于OkHttpClient使用的问题。对于每个请求,它应该是持久的(静态的),还是我应该为每个请求创建一个新的实例?@StErMi您应该为所有请求使用相同的实例。查看Jakes Wharton对此帖子的回复(plus.google.com/118239425803358296962/posts/5nzAvPaitHu),这是一个比公认答案更干净的解决方案。我在改型时使用它,效果很好。Proguard和reflection不能很好地混合,因此在Proguard配置中添加“-keep public class package.SerializableHttpCookie{*;}”会有帮助。有关okhttp3,请参阅:
OkHttpClient client = new OkHttpClient();
client.setCookieHandler(new CookieManager(
new PersistentCookieStore(getApplicationContext()),
CookiePolicy.ACCEPT_ALL));