Volley Session的小結(jié)

標簽(空格分隔): Volley Session小結(jié)


Volley創(chuàng)建過程

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
    File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);
    String userAgent = "volley/0";
    try {
        String packageName = context.getPackageName();
        PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
        userAgent = packageName + "/" + info.versionCode;
    } catch (NameNotFoundException e) {
    }
    if (stack == null) {
        if (Build.VERSION.SDK_INT >= 9) {
            stack = new HurlStack();
        } else {
            // Prior to Gingerbread, HttpUrlConnection was unreliable.
            // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
            stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        }
    }
    Network network = new BasicNetwork(stack);
    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
    queue.start();
    return queue;
}

Volley默認給出了兩種創(chuàng)建方式颅围,其中HurlStack對應(yīng)HttpURLConnection秸弛,而HttpClientStack對應(yīng)于HttpClient.默認情況下坯墨,Volley是不支持Cookies和Session的禁舷。這兩種情況下添加session支持的方式如下违霞。

兩種方式對Session支持:
1.HttpURLConnection方式

CookieManager cookieManager = new CookieManager(  );
CookieHandler.setDefault( cookieManager );
RequestQueue mRequestQueue = Volley.newRequestQueue( context )

添加一個CookieManager即可讓HttpURLConnection支持session,在HttpURLConnectionImpl實現(xiàn)類中OkHttpClient會引用這個cookiemanager對象佳镜。均為java.net包下提供。這種方式目前沒有并發(fā)問題姊氓,下面來看看另外一種丐怯。

2.HttpClient方式

//自定義一個PreferencesCookieStore對象,把cookie值本地化存起來
HttpClient defaultHttpClient = new DefaultHttpClient();
CookieStore cookieStore = new PreferencesCookieStore( context );
defaultHttpClient.setCookieStore( cookieStore );
HttpStack httpStack = new HttpClientStack( defaultHttpClient );
RequestQueue mRequestQueue = Volley.newRequestQueue( context, httpStack );

但是有一個嚴重問題使用這種方式之后,網(wǎng)絡(luò)請求由httpClient執(zhí)行翔横,我們會失去Volley一個很重要的并發(fā)功能读跷,因為我們使用的是HttpClient的一個單例,我們必須遵守它的規(guī)則禾唁,同一個實例下一個請求必須在上一個請求已經(jīng)結(jié)束情況下才行效览。很顯然无切,這樣使用Volley并發(fā)的問題在實際開發(fā)中完全不能滿足我們的需要。下面是一種改良法丐枉,經(jīng)我測試哆键,只不過是加上的等待機制,對于真正并發(fā)來說效率低了許多瘦锹。
如下:

DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
ClientConnectionManager mClientConnectionManager = defaultHttpClient.getConnectionManager();
HttpParams mHttpParams = defaultHttpClient.getParams();
ThreadSafeClientConnManager mThreadSafeClientConnManager = new ThreadSafeClientConnManager( mHttpParams,       
mClientConnectionManager.getSchemeRegistry() );
defaultHttpClient = new DefaultHttpClient( mThreadSafeClientConnManager, mHttpParams );
CookieStore cookieStore = new PreferencesCookieStore( context );
defaultHttpClient.setCookieStore( cookieStore );
HttpStack httpStack = new HttpClientStack( defaultHttpClient );
mRequestQueue = Volley.newRequestQueue( context, httpStack );

關(guān)于HttpClient的Cookie機制簡要說明责鳍,假設(shè)cookie保存在本地昼蛀,當去請求一個網(wǎng)址的時候违寞,request會獲取本地的cookie對象(CookieStore.getCookies())纵潦,即是我們代碼中setCookieStore設(shè)置的,第一次,本地cookie是空听绳,這個時候服務(wù)器給回response的時候颂碘,會根據(jù)規(guī)則判斷是否要往本地寫cookie (CookieStore.addCookie(Cookie)),第一次顯然會將當前這次連接的cookie信息保存下來椅挣。以后再由請求的時候头岔,即能從本地中獲取cookie去請求了,當然整個過程復雜度是比較高的

eg:自定義PreferencesCookieStore如下

PreferencesCookieStore.java

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 保存到 Preferences 的cookie
 *
 */
public class PreferencesCookieStore implements CookieStore {

  private static final String COOKIE_PREFS = "CookiePrefsFile";
  private static final String COOKIE_NAME_STORE = "names";
  private static final String COOKIE_NAME_PREFIX = "cookie_";

  private final ConcurrentHashMap<String, Cookie> cookies;
  private final SharedPreferences cookiePrefs;

  /**
   * Construct a persistent cookie store.
   */
  public PreferencesCookieStore(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) {
    String name = cookie.getName();

    // 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 local store
    cookies.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();
  }

  @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)) {
        // 清除cookies
        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());
  }



  protected String encodeCookie(SerializableCookie cookie) {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
      ObjectOutputStream outputStream = new ObjectOutputStream(os);
      outputStream.writeObject(cookie);
    } catch (Exception e) {
      return null;
    }

    return byteArrayToHexString(os.toByteArray());
  }

  protected Cookie decodeCookie(String cookieStr) {
    byte[] bytes = hexStringToByteArray(cookieStr);
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    Cookie cookie = null;
    try {
      ObjectInputStream ois = new ObjectInputStream(is);
      cookie = ((SerializableCookie)ois.readObject()).getCookie();
    } catch (Exception e) {
      e.printStackTrace();
    }

    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!
  protected String byteArrayToHexString(byte[] b) {
    StringBuffer sb = new StringBuffer(b.length * 2);
    for (byte element : b) {
      int v = element & 0xff;
      if(v < 16) {
        sb.append('0');
      }
      sb.append(Integer.toHexString(v));
    }
    return sb.toString().toUpperCase();
  }

  protected byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for(int i=0; i<len; i+=2) {
      data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16));
    }
    return data;
  }


  public class SerializableCookie implements Serializable {
    private static final long serialVersionUID = 6374381828722046732L;

    private transient final Cookie cookie;
    private transient BasicClientCookie clientCookie;

    public SerializableCookie(Cookie cookie) {
      this.cookie = cookie;
    }

    public Cookie getCookie() {
      Cookie 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.getDomain());
      out.writeObject(cookie.getExpiryDate());
      out.writeObject(cookie.getPath());
      out.writeInt(cookie.getVersion());
      out.writeBoolean(cookie.isSecure());
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
      String name = (String)in.readObject();
      String value = (String)in.readObject();
      clientCookie = new BasicClientCookie(name, value);
      clientCookie.setComment((String)in.readObject());
      clientCookie.setDomain((String)in.readObject());
      clientCookie.setExpiryDate((Date)in.readObject());
      clientCookie.setPath((String)in.readObject());
      clientCookie.setVersion(in.readInt());
      clientCookie.setSecure(in.readBoolean());
    }
  }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鼠证,一起剝皮案震驚了整個濱河市峡竣,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌名惩,老刑警劉巖澎胡,帶你破解...
    沈念sama閱讀 206,214評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件孕荠,死亡現(xiàn)場離奇詭異娩鹉,居然都是意外死亡,警方通過查閱死者的電腦和手機稚伍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,307評論 2 382
  • 文/潘曉璐 我一進店門弯予,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人个曙,你說我怎么就攤上這事锈嫩。” “怎么了垦搬?”我有些...
    開封第一講書人閱讀 152,543評論 0 341
  • 文/不壞的土叔 我叫張陵呼寸,是天一觀的道長。 經(jīng)常有香客問我猴贰,道長对雪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,221評論 1 279
  • 正文 為了忘掉前任米绕,我火速辦了婚禮瑟捣,結(jié)果婚禮上馋艺,老公的妹妹穿的比我還像新娘。我一直安慰自己迈套,他們只是感情好捐祠,可當我...
    茶點故事閱讀 64,224評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著桑李,像睡著了一般踱蛀。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上贵白,一...
    開封第一講書人閱讀 49,007評論 1 284
  • 那天星岗,我揣著相機與錄音,去河邊找鬼戒洼。 笑死俏橘,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的圈浇。 我是一名探鬼主播寥掐,決...
    沈念sama閱讀 38,313評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼磷蜀!你這毒婦竟也來了召耘?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,956評論 0 259
  • 序言:老撾萬榮一對情侶失蹤褐隆,失蹤者是張志新(化名)和其女友劉穎污它,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體庶弃,經(jīng)...
    沈念sama閱讀 43,441評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡衫贬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,925評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了歇攻。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片固惯。...
    茶點故事閱讀 38,018評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖缴守,靈堂內(nèi)的尸體忽然破棺而出葬毫,到底是詐尸還是另有隱情,我是刑警寧澤屡穗,帶...
    沈念sama閱讀 33,685評論 4 322
  • 正文 年R本政府宣布贴捡,位于F島的核電站,受9級特大地震影響村砂,放射性物質(zhì)發(fā)生泄漏烂斋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,234評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望源祈。 院中可真熱鬧煎源,春花似錦、人聲如沸香缺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,240評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽图张。三九已至锋拖,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間祸轮,已是汗流浹背兽埃。 一陣腳步聲響...
    開封第一講書人閱讀 31,464評論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留适袜,地道東北人柄错。 一個月前我還...
    沈念sama閱讀 45,467評論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像苦酱,于是被迫代替她去往敵國和親售貌。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,762評論 2 345

推薦閱讀更多精彩內(nèi)容