Volley Session的小结

标签(空格分隔): Volley Session小结


Volley创建过程

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默认给出了两种创建方式,其中HurlStack对应HttpURLConnection,而HttpClientStack对应于HttpClient.默认情况下,Volley是不支持Cookies和Session的。这两种情况下添加session支持的方式如下。

两种方式对Session支持:
1.HttpURLConnection方式

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

添加一个CookieManager即可让HttpURLConnection支持session,在HttpURLConnectionImpl实现类中OkHttpClient会引用这个cookiemanager对象。均为java.net包下提供。这种方式目前没有并发问题,下面来看看另外一种。

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 );

但是有一个严重问题使用这种方式之后,网络请求由httpClient执行,我们会失去Volley一个很重要的并发功能,因为我们使用的是HttpClient的一个单例,我们必须遵守它的规则,同一个实例下一个请求必须在上一个请求已经结束情况下才行。很显然,这样使用Volley并发的问题在实际开发中完全不能满足我们的需要。下面是一种改良法,经我测试,只不过是加上的等待机制,对于真正并发来说效率低了许多。
如下:

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 );

关于HttpClient的Cookie机制简要说明,假设cookie保存在本地,当去请求一个网址的时候,request会获取本地的cookie对象(CookieStore.getCookies()),即是我们代码中setCookieStore设置的,第一次,本地cookie是空,这个时候服务器给回response的时候,会根据规则判断是否要往本地写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());
    }
  }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容