Android OkHttp的Cookie自己主动化管理
Android中在使用OkHttp这个库的时候。有时候须要持久化Cookie,那么怎么实现呢。OkHttp的内部源代码过于复杂,不进行深究。这里仅仅看当中的HttpEngineer里面的部分源代码,在发起请求以及请求结束都会调用这个类的几个方法。
我们先看networkRequest方法。在里面通过client.getCookieHandler()函数获得了CookieHandler对象。通过该对象拿到cookie并设置到请求头里,请求结束后取得响应后通过networkResponse.headers()函数将请求头获得传入receiveHeaders函数,并将取得的cookie存入getCookieHandler得到的一个CookieHandler对象中去
This client doesn't specify a default {@code Accept} header because it * doesn't know what content types the application is interested in. */ private Request networkRequest(Request request) throws IOException { Request.Builder result = request.newBuilder(); //此处省略n行代码...... CookieHandler cookieHandler = client.getCookieHandler(); if (cookieHandler != null) { // Capture the request headers added so far so that they can be offered to the CookieHandler. // This is mostly to stay close to the RI; it is unlikely any of the headers above would // affect cookie choice besides "Host". Map headers = OkHeaders.toMultimap(result.build().headers(), null); Map cookies = cookieHandler.get(request.uri(), headers); // Add any new cookies to the request. OkHeaders.addCookies(result, cookies); } //此处省略n行代码...... return result.build(); }" data-snippet-id="ext.4df17b386793c68468195a690c917859" data-snippet-saved="false" data-csrftoken="bFkHGE1O-cy7WY9D6w70F6qK9YUKZHLynI5g" data-codota-status="done">[code]/** * Populates request with defaults and cookies. * * <p>This client doesn't specify a default {@code Accept} header because it * doesn't know what content types the application is interested in. */ private Request networkRequest(Request request) throws IOException { Request.Builder result = request.newBuilder(); //此处省略n行代码...... CookieHandler cookieHandler = client.getCookieHandler(); if (cookieHandler != null) { // Capture the request headers added so far so that they can be offered to the CookieHandler. // This is mostly to stay close to the RI; it is unlikely any of the headers above would // affect cookie choice besides "Host". Map<String, List<String>> headers = OkHeaders.toMultimap(result.build().headers(), null); Map<String, List<String>> cookies = cookieHandler.get(request.uri(), headers); // Add any new cookies to the request. OkHeaders.addCookies(result, cookies); } //此处省略n行代码...... return result.build(); }
public void readResponse() throws IOException { //此处省略n行代码...... receiveHeaders(networkResponse.headers()); //此处省略n行代码...... }
public void receiveHeaders(Headers headers) throws IOException { CookieHandler cookieHandler = client.getCookieHandler(); if (cookieHandler != null) { cookieHandler.put(userRequest.uri(), OkHeaders.toMultimap(headers, null)); } }
而这个CookieHandler对象是OkHttpClient类中的一个属性,提供了getter和setter方法,默认的构造函数OkHttpClient client = new OkHttpClient();不会创建这个CookieHandler对象。如果我们传入了这个对象。那么OkHttp自然会进行cookie的自己主动管理了。
private CookieHandler cookieHandler; public OkHttpClient setCookieHandler(CookieHandler cookieHandler) { this.cookieHandler = cookieHandler; return this; } public CookieHandler getCookieHandler() { return cookieHandler; }
那么如果我们将CookieHandler对象传入
OkHttpClient client = new OkHttpClient(); client.setCookieHandler(CookieHandler cookieHanlder);
那么,如今关键是怎样去实现这个CookieHandler 对象。CookieManager是CookieHandler 的一个子类,其构造函数 public CookieManager(CookieStore store, CookiePolicy cookiePolicy)须要传入两个參数,CookieStore 是一个接口,因此我们实现CookieStore接口中的抽象方法。就可以实现这个CookieHandler 对象。
參考android-async-http这个库,它具有cookie的自己主动管理功能。主要我们參考当中的两个类
參考以上两个类并做适当改动,得到了例如以下两个类,他们的功能就是将cookie保持在SharedPreferences中。
package com.kltz88.okhttp.cookie; /** * User:lizhangqu(513163535@qq.com) * Date:2015-07-13 * Time: 17:31 */ 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()); } }[code]> 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(); // Load any previously stored cookies into the store Map prefsMap = cookiePrefs.getAll(); for(Map.Entry 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()); 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()); 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 get(URI uri) { ArrayList ret = new ArrayList(); 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 getCookies() { ArrayList ret = new ArrayList(); for (String key : cookies.keySet()) ret.addAll(cookies.get(key).values()); return ret; } @Override public List getURIs() { ArrayList ret = new ArrayList(); 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)
- Android-HttpURLConnection自己主动管理cookie
- Android OkHttp的Cookie自动化管理
- Android使用OkHttp携带Cookie请求数据,并对Cookie进行持久化管理
- 如何管理app的进程与内存分配,以及在Android开发应用的时候如何主动的减少内存的使用
- cocos2dx 自己主动加入cpp文件到android.mk
- 【Android】Android程序自己主动更新
- android登录Web以及登录保持,cookie管理相关
- 二维码URL自己主动辨别Android和ISO设备,以便扫码后倒入不同的下载链接
- 自己封装双缓存管理框架Android 库
- 使用Adt自带的工具进行Android自己主动化測试(三)
- Eclipse下配置Ant脚本 自己主动打包带签名的Android apk
- [Android] AutoCompleteTextView:自己主动完毕输入内容的控件(自己主动补全)
- Android数据自己主动更新库DataAutoRefresh
- Android Okhttp框架获取cookie
- Cocos2d-x3.1下 Android,APK自己主动升级
- android 自己主动拒接后再取消自己主动拒接,该联系人来电界面无图标显示,且点击挂断无反应
- Android 6.0 的权限管理自己简单的封装--(到BaseActivity)
- android 视频通话开启呼叫等待后,来第三方的视频通话,接通后通话时间一直显示为0,过几秒之后视频通话自己主动挂断
- okHttp管理cookie的简单方法
- [Android实例] android登录Web以及登录保持,cookie管理相关