Android 中okHttp的cookie
2015-11-10 15:55
549 查看
1.public static OkHttpClient mOkHttpClient=new OkHttpClient();确保okhttpclient对象只有一个。
2.在请求网络之前执行:
OkHttpClient client = OkhttpRequest.mOkHttpClient; client.setCookieHandler(new CookieManager( new PersistentCookieStore(getApplicationContext()), CookiePolicy.ACCEPT_ALL));3.
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); } }
4.
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; } }
5.
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()); } }另外:
public class OkhttpRequest { public static OkHttpClient mOkHttpClient; private static OkhttpRequest mInstance; //私有化构造器; private OkhttpRequest() { mOkHttpClient=new OkHttpClient(); mOkHttpClient.setCookieHandler(new CookieManager(new PersistentCookieStore(MyApplication.getContext()), CookiePolicy.ACCEPT_ALL)); } //返回单例; public static OkhttpRequest getInstance(){ if (mInstance==null){ synchronized (OkhttpRequest.class){ if (mInstance==null){ mInstance=new OkhttpRequest(); } } } return mInstance; } // public void getRequest(String url, ProgressDialog dialog, MyCallBack2 callback) { // dialog.show(); ////创建一个Request // Request request = new Request.Builder() // .url(url) // .build(); ////请求加入调度 // mOkHttpClient.newCall(request).enqueue(callback); // } public void getRequest(String url, ProgressDialog dialog, MyCallBack callback) { dialog.show(); //创建一个Request Request request = new Request.Builder() .url(url) .build(); //请求加入调度 mOkHttpClient.newCall(request).enqueue(callback); } public void postRequest(String url,RequestBody body,ProgressDialog dialog, MyCallBack callback) { dialog.show(); Request request = new Request.Builder() .url(url) .post(body) .build(); mOkHttpClient.newCall(request).enqueue(callback); } }
相关文章推荐
- 网络江湖的内外八门
- TCP的SEQ和ACK的生成
- 如何在IIS7或IIS7.5中导入导出站点及应用程序池. -摘自网络
- http协议
- 网络层如何解耦问题
- HTTP协议详解学习笔记
- <网络编程培训之四> 编写一个UDP聊天室
- Android 判断网络状态,并且在没有网络的时候,打开网络设置对话框
- Java模拟HttpClient进行Get和Post提交
- App Transport Security has blocked a cleartext HTTP (http://) resource load
- iOS 开发网络数据处理 ------ AFNetWorking
- HttpWebResponse 传输IDictionary<string, string>[] parameter数组
- HTTP 状态码整理
- android GridView 通过json显示网络图片和文字
- (转)TDI FILTER 网络过滤驱动完全解析
- 搭建入门网络验证码(注册码)教程
- 如何在Ant中设置HTTP代理
- Android网络数据请求之HttpClient
- 在Spring Boot中使用Https
- Zigbee网关作为tcpclient示意图