android 持久化保存cookie

来源:互联网 发布:知彼而知己 打不开 编辑:程序博客网 时间:2024/05/01 11:03

在解析网页信息的时候,需要登录后才能访问,所以使用httpclient模拟登录,然后把cookie保存下来,以供下一次访问使用,这时就需要持久化cookie中的内容。

一、请求网络获取cookie

先看一下下面的代码:

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:14px;"><span style="white-space:pre">    </span>  DefaultHttpClient httpclient = new DefaultHttpClient();  
  2.           HttpGet httpget = new HttpGet("http://www.hlovey.com");  
  3.           HttpResponse response = httpclient.execute(httpget);  
  4.           HttpEntity entity = response.getEntity();  
  5.           List<Cookie> cookies = httpclient.getCookieStore().getCookies();</span>  
Post模拟登录

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="white-space:pre">    </span>HttpPost httpPost = new HttpPost(url);  
  2.         List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
  3.         formparams.add(new BasicNameValuePair("id", userid));  
  4.         formparams.add(new BasicNameValuePair("passwd", passwd));  
  5.         UrlEncodedFormEntity entity;  
  6.         try {  
  7.             entity = new UrlEncodedFormEntity(formparams, mobileSMTHEncoding);  
  8.         } catch (UnsupportedEncodingException e1) {  
  9.             return 3;  
  10.         }  
  11.         httpPost.setEntity(entity);  
  12.         httpPost.setHeader("User-Agent", userAgent);  
  13.         HttpResponse response = httpClient.execute(httpPost);  
二、保存cookie

保存cookie有两种方式一种是数据库,另一种是SharedPreferences,其中http://blog.csdn.net/junjieking/article/details/7658551是使用数据库来保存的,这里我是使用SharedPreferences保存。

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="white-space:pre">    </span>package com.smthbest.smth.util;  
  2.   
  3. <span style="white-space:pre">    </span>import java.util.Locale;  
  4.         import android.content.Context;  
  5.         import android.content.SharedPreferences;  
  6.         import android.text.TextUtils;  
  7.         import android.util.Log;  
  8.   
  9.         import org.apache.http.client.CookieStore;  
  10.         import org.apache.http.cookie.Cookie;  
  11.   
  12.         import java.io.ByteArrayInputStream;  
  13.         import java.io.ByteArrayOutputStream;  
  14.         import java.io.ObjectInputStream;  
  15.         import java.io.ObjectOutputStream;  
  16.         import java.util.ArrayList;  
  17.         import java.util.Date;  
  18.         import java.util.List;  
  19.         import java.util.Locale;  
  20.         import java.util.concurrent.ConcurrentHashMap;  
  21.   
  22.   
  23. public class PersistentCookieStore implements CookieStore {  
  24.     private static final String LOG_TAG = "PersistentCookieStore";  
  25.     private static final String COOKIE_PREFS = "CookiePrefsFile";  
  26.     private static final String COOKIE_NAME_STORE = "names";  
  27.     private static final String COOKIE_NAME_PREFIX = "cookie_";  
  28.     private boolean omitNonPersistentCookies = false;  
  29.   
  30.     private final ConcurrentHashMap<String, Cookie> cookies;  
  31.     private final SharedPreferences cookiePrefs;  
  32.   
  33.     /** 
  34.      * Construct a persistent cookie store. 
  35.      * 
  36.      * @param context Context to attach cookie store to 
  37.      */  
  38.     public PersistentCookieStore(Context context) {  
  39.         cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);  
  40.         cookies = new ConcurrentHashMap<String, Cookie>();  
  41.   
  42.         // Load any previously stored cookies into the store  
  43.         String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);  
  44.         if (storedCookieNames != null) {  
  45.             String[] cookieNames = TextUtils.split(storedCookieNames, ",");  
  46.             for (String name : cookieNames) {  
  47.                 String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);  
  48.                 if (encodedCookie != null) {  
  49.                     Cookie decodedCookie = decodeCookie(encodedCookie);  
  50.                     if (decodedCookie != null) {  
  51.                         cookies.put(name, decodedCookie);  
  52.                     }  
  53.                 }  
  54.             }  
  55.   
  56.             // Clear out expired cookies  
  57.             clearExpired(new Date());  
  58.         }  
  59.     }  
  60.   
  61.     @Override  
  62.     public void addCookie(Cookie cookie) {  
  63.         if (omitNonPersistentCookies && !cookie.isPersistent())  
  64.             return;  
  65.         String name = cookie.getName() + cookie.getDomain();  
  66.   
  67.         // Save cookie into local store, or remove if expired  
  68.         if (!cookie.isExpired(new Date())) {  
  69.             cookies.put(name, cookie);  
  70.         } else {  
  71.             cookies.remove(name);  
  72.         }  
  73.   
  74.         // Save cookie into persistent store  
  75.         SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  
  76.         prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));  
  77.         prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));  
  78.         prefsWriter.commit();  
  79.     }  
  80.   
  81.     @Override  
  82.     public void clear() {  
  83.         // Clear cookies from persistent store  
  84.         SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  
  85.         for (String name : cookies.keySet()) {  
  86.             prefsWriter.remove(COOKIE_NAME_PREFIX + name);  
  87.         }  
  88.         prefsWriter.remove(COOKIE_NAME_STORE);  
  89.         prefsWriter.commit();  
  90.   
  91.         // Clear cookies from local store  
  92.         cookies.clear();  
  93.     }  
  94.   
  95.     @Override  
  96.     public boolean clearExpired(Date date) {  
  97.         boolean clearedAny = false;  
  98.         SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  
  99.   
  100.         for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {  
  101.             String name = entry.getKey();  
  102.             Cookie cookie = entry.getValue();  
  103.             if (cookie.isExpired(date)) {  
  104.                 // Clear cookies from local store  
  105.                 cookies.remove(name);  
  106.   
  107.                 // Clear cookies from persistent store  
  108.                 prefsWriter.remove(COOKIE_NAME_PREFIX + name);  
  109.   
  110.                 // We've cleared at least one  
  111.                 clearedAny = true;  
  112.             }  
  113.         }  
  114.   
  115.         // Update names in persistent store  
  116.         if (clearedAny) {  
  117.             prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));  
  118.         }  
  119.         prefsWriter.commit();  
  120.   
  121.         return clearedAny;  
  122.     }  
  123.   
  124.     @Override  
  125.     public List<Cookie> getCookies() {  
  126.         return new ArrayList<Cookie>(cookies.values());  
  127.     }  
  128.   
  129.     /** 
  130.      * Will make PersistentCookieStore instance ignore Cookies, which are non-persistent by 
  131.      * signature (`Cookie.isPersistent`) 
  132.      * 
  133.      * @param omitNonPersistentCookies true if non-persistent cookies should be omited 
  134.      */  
  135.     public void setOmitNonPersistentCookies(boolean omitNonPersistentCookies) {  
  136.         this.omitNonPersistentCookies = omitNonPersistentCookies;  
  137.     }  
  138.   
  139.     /** 
  140.      * Non-standard helper method, to delete cookie 
  141.      * 
  142.      * @param cookie cookie to be removed 
  143.      */  
  144.     public void deleteCookie(Cookie cookie) {  
  145.         String name = cookie.getName();  
  146.         cookies.remove(name);  
  147.         SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  
  148.         prefsWriter.remove(COOKIE_NAME_PREFIX + name);  
  149.         prefsWriter.commit();  
  150.     }  
  151.   
  152.     /** 
  153.      * Serializes Cookie object into String 
  154.      * 
  155.      * @param cookie cookie to be encoded, can be null 
  156.      * @return cookie encoded as String 
  157.      */  
  158.     protected String encodeCookie(SerializableCookie cookie) {  
  159.         if (cookie == null)  
  160.             return null;  
  161.         ByteArrayOutputStream os = new ByteArrayOutputStream();  
  162.         try {  
  163.             ObjectOutputStream outputStream = new ObjectOutputStream(os);  
  164.             outputStream.writeObject(cookie);  
  165.         } catch (Exception e) {  
  166.             return null;  
  167.         }  
  168.   
  169.         return byteArrayToHexString(os.toByteArray());  
  170.     }  
  171.   
  172.     /** 
  173.      * Returns cookie decoded from cookie string 
  174.      * 
  175.      * @param cookieString string of cookie as returned from http request 
  176.      * @return decoded cookie or null if exception occured 
  177.      */  
  178.     protected Cookie decodeCookie(String cookieString) {  
  179.         byte[] bytes = hexStringToByteArray(cookieString);  
  180.         ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);  
  181.         Cookie cookie = null;  
  182.         try {  
  183.             ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);  
  184.             cookie = ((SerializableCookie) objectInputStream.readObject()).getCookie();  
  185.         } catch (Exception exception) {  
  186.             Log.d(LOG_TAG, "decodeCookie failed", exception);  
  187.         }  
  188.   
  189.         return cookie;  
  190.     }  
  191.   
  192.     /** 
  193.      * Using some super basic byte array <-> hex conversions so we don't have to rely on any 
  194.      * large Base64 libraries. Can be overridden if you like! 
  195.      * 
  196.      * @param bytes byte array to be converted 
  197.      * @return string containing hex values 
  198.      */  
  199.     protected String byteArrayToHexString(byte[] bytes) {  
  200.         StringBuilder sb = new StringBuilder(bytes.length * 2);  
  201.         for (byte element : bytes) {  
  202.             int v = element & 0xff;  
  203.             if (v < 16) {  
  204.                 sb.append('0');  
  205.             }  
  206.             sb.append(Integer.toHexString(v));  
  207.         }  
  208.         return sb.toString().toUpperCase(Locale.US);  
  209.     }  
  210.   
  211.     /** 
  212.      * Converts hex values from strings to byte arra 
  213.      * 
  214.      * @param hexString string of hex-encoded values 
  215.      * @return decoded byte array 
  216.      */  
  217.     protected byte[] hexStringToByteArray(String hexString) {  
  218.         int len = hexString.length();  
  219.         byte[] data = new byte[len / 2];  
  220.         for (int i = 0; i < len; i += 2) {  
  221.             data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));  
  222.         }  
  223.         return data;  
  224.     }  
  225. }  
使用PersistentCookieStore来存储cookie,首先最好把PersistentCookieStore放在Application获取其他的地方,取得唯一实例,保存cookie是在登录成功后,从下面代码获取保存。

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="white-space:pre">    </span>PersistentCookieStore myCookieStore = App.getInstance().getPersistentCookieStore();  
  2.         List<Cookie> cookies = httpClient.getCookieStore().getCookies();  
  3.         for (Cookie cookie:cookies){  
  4.             myCookieStore.addCookie(cookie);  
  5.         }  

三、cookie的使用

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. PersistentCookieStore cookieStore = new PersistentCookieStore(SmthBestApp.getInstance().getApplicationContext());  
  2. httpClient.setCookieStore(cookieStore);  
  3. HttpResponse response = httpClient.execute(httpget);  
这样就可以免再次登录了。

四、SerializableCookie

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. /** 
  2.  * A wrapper class around {@link org.apache.http.cookie.Cookie} and/or {@link org.apache.http.impl.cookie.BasicClientCookie} designed for use in {@link 
  3.  * PersistentCookieStore}. 
  4.  */  
  5. public class SerializableCookie implements Serializable {  
  6.     private static final long serialVersionUID = 6374381828722046732L;  
  7.   
  8.     private transient final Cookie cookie;  
  9.     private transient BasicClientCookie clientCookie;  
  10.   
  11.     public SerializableCookie(Cookie cookie) {  
  12.         this.cookie = cookie;  
  13.     }  
  14.   
  15.     public Cookie getCookie() {  
  16.         Cookie bestCookie = cookie;  
  17.         if (clientCookie != null) {  
  18.             bestCookie = clientCookie;  
  19.         }  
  20.         return bestCookie;  
  21.     }  
  22.   
  23.     private void writeObject(ObjectOutputStream out) throws IOException {  
  24.         out.writeObject(cookie.getName());  
  25.         out.writeObject(cookie.getValue());  
  26.         out.writeObject(cookie.getComment());  
  27.         out.writeObject(cookie.getDomain());  
  28.         out.writeObject(cookie.getExpiryDate());  
  29.         out.writeObject(cookie.getPath());  
  30.         out.writeInt(cookie.getVersion());  
  31.         out.writeBoolean(cookie.isSecure());  
  32.     }  
  33.   
  34.     private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {  
  35.         String name = (String) in.readObject();  
  36.         String value = (String) in.readObject();  
  37.         clientCookie = new BasicClientCookie(name, value);  
  38.         clientCookie.setComment((String) in.readObject());  
  39.         clientCookie.setDomain((String) in.readObject());  
  40.         clientCookie.setExpiryDate((Date) in.readObject());  
  41.         clientCookie.setPath((String) in.readObject());  
  42.         clientCookie.setVersion(in.readInt());  
  43.         clientCookie.setSecure(in.readBoolean());  
  44.     }  
  45. }  
0 0
原创粉丝点击