国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統(tǒng) > Android > 正文

Android持久化保存cookie的方法

2019-10-22 18:10:52
字體:
來源:轉載
供稿:網(wǎng)友

在解析網(wǎng)頁信息的時候,需要登錄后才能訪問,所以使用httpclient模擬登錄,然后把cookie保存下來,以供下一次訪問使用,這時就需要持久化cookie中的內容。

在之前先科普一下基礎知識:

什么是Cookies?

Cookies是一些小文件,它們被創(chuàng)建在客戶端的系統(tǒng)里,或者被創(chuàng)建在客戶端瀏覽器的內存中(如果是臨時性的話)。用它可以實現(xiàn)狀態(tài)管理的功能。我們可以存儲一些少量信息到可以短的系統(tǒng)上,以便在需要的時候使用。最有趣的事情是,它是對用戶透明的。在你的web應用程序中,你可以到處使用它,它極其得簡單。Cookies是以文本形式存儲的。如果一個web應用程序使用cookies,那么服務器負責發(fā)送cookies,客戶端瀏覽器將存儲它。瀏覽器在下次請求頁面的時候,會返回cookies給服務器。最常用的例子是,使用一個cookie來存儲用戶信息,用戶的喜好,“記住密碼”操作等。Cookies有許多優(yōu)點,當然也有許多缺點。我將在接下來講述。

Cookies是如何創(chuàng)建的?

當一個客戶端向服務器發(fā)出請求,服務器發(fā)送cookies給客戶端。而相同的cookies可以被后續(xù)的請求使用。例如,如果codeproject.com將Session ID作為cookies存儲。當一個客戶端首次向web服務器請求頁面,服務器生成Session ID,并將其作為cookies發(fā)送往客戶端。

android,cookie,持久化

現(xiàn)在,所有來自相同客戶端的后續(xù)請求,它將使用來自cookies的Session ID,就像下面這幅圖片展示的那樣。

android,cookie,持久化

瀏覽器和web服務器以交換cookies信息來作為響應。對不同的站點,瀏覽器會維護不同的cookies。如果一個頁面需要cookies中的信息,當某個URL被“點擊”,首先瀏覽器將搜索本地系統(tǒng)的cookies的信息,然后才轉向服務器來獲得信息。

Cookies的優(yōu)勢

下面是使用cookies的主要優(yōu)勢:

(1)    實現(xiàn)和使用都是非常簡單的

(2)    由瀏覽器來負責維護發(fā)送過來的數(shù)據(jù)(cookies內容)

(3)    對來自多個站點的cookies來講,瀏覽器自動管理它們

Cookies的劣勢

下面是cookies的主要劣勢:

(1)    它以簡單的文本格式來存儲數(shù)據(jù),所以它一點也不安全

(2)    對于cookies數(shù)據(jù),有大小限制(4kB)

(3)    Cookies最大數(shù)目也有限制。主流瀏覽器提供將cookies的個數(shù)限制在20條。如果新cookies到來,那么老的將被刪除。有些瀏覽器能支持到300條的cookies數(shù)。

(4)    我們需要配置瀏覽器,cookies將不能工作在瀏覽器配置的高安全級別環(huán)境下。

什么是持久化的和非持久化的Cookies

我們可以將cookies分成兩類:

(1)    持久化的cookies

(2)    非持久化的cookies

持久化的cookies:這可以被稱為永久性的cookies,它被存儲在客戶端的硬盤內,直到它們失效。持久化的cookies應該被設置一個失效時間。有時,它們會一直存在直到用戶刪除它們。持久化的cookies通常被用來為某個系統(tǒng)收集一個用戶的標識信息。

非持久化cookies:也可以被稱之為臨時性的cookies。如果沒有定義失效時間,那么cookie將會被存儲在瀏覽器的內存中。我上面展示的例子就是一個非持久的cookies。

修改一個持久化的cookies與一個非持久化的cookies并沒有什么不同。它們唯一的區(qū)別是——持久化的cookies有一個失效時間的設置。

Cookie持久化

HttpClient可以和任意物理表示的實現(xiàn)了CookieStore接口的持久化cookie存儲一起使用。默認的CookieStore實現(xiàn)稱為BasicClientCookie,這是憑借java.util.ArrayList的一個簡單實現(xiàn)。在BasicClientCookie對象中存儲的cookie當容器對象被垃圾回收機制回收時會丟失。如果需要,用戶可以提供更復雜的實現(xiàn)。

下載著重介紹在安卓中如何利用httpclient來實現(xiàn)對cookie的持久化操作:

一、請求網(wǎng)絡獲取cookie

先看一下下面的代碼:

DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://www.hlovey.com"); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); 

Post模擬登錄

HttpPost httpPost = new HttpPost(url); List<NameValuePair> formparams = new ArrayList<NameValuePair>(); formparams.add(new BasicNameValuePair("id", userid)); formparams.add(new BasicNameValuePair("passwd", passwd)); UrlEncodedFormEntity entity; try {  entity = new UrlEncodedFormEntity(formparams, mobileSMTHEncoding); } catch (UnsupportedEncodingException e1) {  return 3; } httpPost.setEntity(entity); httpPost.setHeader("User-Agent", userAgent); HttpResponse response = httpClient.execute(httpPost); 

二、保存cookie

保存cookie有兩種方式一種是數(shù)據(jù)庫,另一種是SharedPreferences,其中http://www.survivalescaperooms.com/article/140423.htm是使用數(shù)據(jù)庫來保存的,這里我是使用SharedPreferences保存。

 package com.smthbest.smth.util;  import java.util.Locale;  import android/286636.html">android.content.Context;  import android.content.SharedPreferences;  import android.text.TextUtils;  import android.util.Log;  import org.apache.http.client.CookieStore;  import org.apache.http.cookie.Cookie;  import java.io.ByteArrayInputStream;  import java.io.ByteArrayOutputStream;  import java.io.ObjectInputStream;  import java.io.ObjectOutputStream;  import java.util.ArrayList;  import java.util.Date;  import java.util.List;  import java.util.Locale;  import java.util.concurrent.ConcurrentHashMap; ic class PersistentCookieStore implements CookieStore { private static final String LOG_TAG = "PersistentCookieStore"; private static final String COOKIE_PREFS = "CookiePrefsFile"; private static final String COOKIE_NAME_STORE = "names"; private static final String COOKIE_NAME_PREFIX = "cookie_"; private boolean omitNonPersistentCookies = false; private final ConcurrentHashMap<String, Cookie> 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 ConcurrentHashMap<String, Cookie>();   // Load any previously stored cookies into the store  String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);  if (storedCookieNames != null) {  String[] cookieNames = TextUtils.split(storedCookieNames, ",");  for (String name : cookieNames) {   String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);   if (encodedCookie != null) {   Cookie decodedCookie = decodeCookie(encodedCookie);   if (decodedCookie != null) {    cookies.put(name, decodedCookie);   }   }  }   // Clear out expired cookies  clearExpired(new Date());  } }  @Override public void addCookie(Cookie cookie) {  if (omitNonPersistentCookies && !cookie.isPersistent())  return;  String name = cookie.getName() + cookie.getDomain();   // Save cookie into local store, or remove if expired  if (!cookie.isExpired(new Date())) {  cookies.put(name, cookie);  } else {  cookies.remove(name);  }   // Save cookie into persistent store  SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));  prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));  prefsWriter.commit(); }  @Override public void clear() {  // Clear cookies from persistent store  SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  for (String name : cookies.keySet()) {  prefsWriter.remove(COOKIE_NAME_PREFIX + name);  }  prefsWriter.remove(COOKIE_NAME_STORE);  prefsWriter.commit();   // Clear cookies from local store  cookies.clear(); }  @Override public boolean clearExpired(Date date) {  boolean clearedAny = false;  SharedPreferences.Editor prefsWriter = cookiePrefs.edit();   for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {  String name = entry.getKey();  Cookie cookie = entry.getValue();  if (cookie.isExpired(date)) {   // Clear cookies from local store   cookies.remove(name);    // Clear cookies from persistent store   prefsWriter.remove(COOKIE_NAME_PREFIX + name);    // We've cleared at least one   clearedAny = true;  }  }   // Update names in persistent store  if (clearedAny) {  prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));  }  prefsWriter.commit();   return clearedAny; }  @Override public List<Cookie> getCookies() {  return new ArrayList<Cookie>(cookies.values()); }  /**  * Will make PersistentCookieStore instance ignore Cookies, which are non-persistent by  * signature (`Cookie.isPersistent`)  *  * @param omitNonPersistentCookies true if non-persistent cookies should be omited  */ public void setOmitNonPersistentCookies(boolean omitNonPersistentCookies) {  this.omitNonPersistentCookies = omitNonPersistentCookies; }  /**  * Non-standard helper method, to delete cookie  *  * @param cookie cookie to be removed  */ public void deleteCookie(Cookie cookie) {  String name = cookie.getName();  cookies.remove(name);  SharedPreferences.Editor prefsWriter = cookiePrefs.edit();  prefsWriter.remove(COOKIE_NAME_PREFIX + name);  prefsWriter.commit(); }  /**  * Serializes Cookie object into String  *  * @param cookie cookie to be encoded, can be null  * @return cookie encoded as String  */ protected String encodeCookie(SerializableCookie cookie) {  if (cookie == null)  return null;  ByteArrayOutputStream os = new ByteArrayOutputStream();  try {  ObjectOutputStream outputStream = new ObjectOutputStream(os);  outputStream.writeObject(cookie);  } catch (Exception 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 Cookie decodeCookie(String cookieString) {  byte[] bytes = hexStringToByteArray(cookieString);  ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);  Cookie cookie = null;  try {  ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);  cookie = ((SerializableCookie) objectInputStream.readObject()).getCookie();  } catch (Exception exception) {  Log.d(LOG_TAG, "decodeCookie failed", exception);  }   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; } 

使用PersistentCookieStore來存儲cookie,首先最好把PersistentCookieStore放在Application獲取其他的地方,取得唯一實例,保存cookie是在登錄成功后,從下面代碼獲取保存。

PersistentCookieStore myCookieStore = App.getInstance().getPersistentCookieStore(); List<Cookie> cookies = httpClient.getCookieStore().getCookies(); for (Cookie cookie:cookies){  myCookieStore.addCookie(cookie); } 

三、cookie的使用

PersistentCookieStore cookieStore = new PersistentCookieStore(SmthBestApp.getInstance().getApplicationContext()); httpClient.setCookieStore(cookieStore); HttpResponse response = httpClient.execute(httpget); 

這樣就可以免再次登錄了。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網(wǎng)。


注:相關教程知識閱讀請移步到Android開發(fā)頻道。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 竹山县| 吉林省| 五大连池市| 商洛市| 双峰县| 竹溪县| 齐齐哈尔市| 清徐县| 广水市| 莎车县| 大连市| 灵山县| 和平县| 黄石市| 广东省| 汝州市| 缙云县| 大理市| 凤山县| 吉木乃县| 兴海县| 慈利县| 余姚市| 孝昌县| 策勒县| 宜黄县| 霸州市| 和龙市| 泰来县| 彭州市| 东方市| 肥城市| 西平县| 齐河县| 上饶市| 堆龙德庆县| 遵义市| 元江| 宜宾县| 威远县| 昭觉县|