Let Android volley support cookie session is actually very simple!
Source: Internet
Author: User
<span id="Label3"></p><p><p>Take a look at the following steps:</p></p><p><p>Instantiate a network communication class with a cookie Defaulthttpclient</p></p><p><p></p></p><pre name="code" class="html"><pre name="code" class="html">/** * Return request queue * @return */private requestqueue getrequestqueue () { if (mrequestqueue = = Null) { defaulthttpclient httpclient = new Defaulthttpclient (); Non-persistent storage (memory Storage) Basiccookiestore | Persistent storage Preferencescookiestore Cookiestore cookiestore = new Preferencescookiestore (this); Httpclient.setcookiestore (cookiestore); Httpstack httpstack = new Httpclientstack (httpclient); Mrequestqueue = Volley.newrequestqueue (getapplicationcontext (), httpstack); } </pre></pre><p><p></p></p><p><p><br></p></p><p><p>There is no detailed description of the definition of cookies here, I think we all understand clearly! First of all, the specific cookie storage implementation principle here is that Android saves the cookie information to the memory card or store it to the server and keeps the session State.</p></p>Cookie storage types are categorized as: persistent storage and non-persistent storage<p><p>The following is the specific implementation code for cookie persistence storage:</p></p><p><p> </p> </p><pre name="code" class="java">Package Org.wavefar.lib.http;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;import Org.apache.http.client.cookiestore;import Org.apache.http.cookie.cookie;import Org.apache.http.impl.cookie.basicclientcookie;import Android.content.context;import Android.content.sharedpreferences;import android.text.textutils;/** * Save to Preferences cookies * @description * @author Summer * @date May 9, 2014 PM 3:11:08 * */public class Preferencescookiestore IM Plements 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 cookie into the store String storedcookienames = cookieprefs.getstring (cookie_name_s tore, null); If (storedcookienames! = Null) {string[] cookienames = textutils.split (storedcookienames, ","); For (string name:cookienames) {string Encodedcookie = cookieprefs.getstring (cookie_name_prefix + name, nu ll); 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 (na me, 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 cookie 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)) {//clears the cookie 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 Bytearrayoutputstrea M (); 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 has//to rely on any largE Base64 Libraries. Can is 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 <) {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), +) << 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 (CookieCookie) {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 ()); } }}</pre><br>The above code enables the Android client to save the cookie session state, the general application scenario for SMS verification or user automatic login, save user-related Information.<p><p></p></p><p><p>Let Android volley support cookie session is actually very simple!</p></p></span>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service