OKHTTP3 's use, the actual combat experience of their own projects

Source: Internet
Author: User
Tags addall

okhttp3.0 on-line information is too little, today I come to write a okhttp3.0 for you to use

A lot of builder was introduced into the okhttp3.0.


1. Create okhttpclient builder


private static final OKHTTP3. Okhttpclient.builder Builder = new Okhttpclient.builder ();


2. Create an instance of Okhttpclient

Setting the time-out setting cookies cache

Mokhttpclient=builder.connecttimeout (timeunit.seconds). Cookiejar (New Cookiesmanager ()). build ();

Private class Cookiesmanager implements Cookiejar  {            private final persistentcookiestore Cookiestore = new Persistentcookiestore (context);        @Override public        void savefromresponse (httpurl url, list<cookie> cookies) {            if (cookies! = null && Cookies.size () > 0) {                for (Cookie item:cookies) {                    cookiestore.add (URL, item);        }}} @Override public        list<cookie> loadforrequest (httpurl url) {            list<cookie> cookies = Cookiestore.get (URL);            return cookies;        }    }

3. Using OkHttpClient3.0

Get Request Object

  private static Request getprarequest (String url,string name) {  Builder builder=  new Formbody.builder (). Add (" Name ", name); Form <span style= "font-family:arial, Helvetica, Sans-serif;" >//through Request.builder () to build () an instance </span>
             return new Request.builder (). URL (URL). Post (Builder.build ()). build (); }

Request URL

Mokhttpclient.newcall (getprarequest (URL, name)). Enqueue (Responsecallback);

getprarequest (URL, name) get a request Responsecallback Callback event is the interface of Callback

public void Onresponse (call arg0, Final Response arg1) throws IOException {if (arg1.issuccessful ()) {try{onsuccess (new Jsonobject (Arg1.body (). String ()));} catch (Jsonexception e) {onfailure ("JSON parsing exception"); E.printstacktrace ();}            Onloginsuccess (null, arg1);} else{           onfailure ("Request failed, return code" + "Arg1.code ()");  System.out.println (Arg1.code () + "");}}

Two categories of cookies

public class Persistentcookiestore {private static final String Log_tag = "Persistentcookiestore";    private static final String cookie_prefs = "Cookies_prefs";    Private final map<string, concurrenthashmap<string, cookie>> cookies;    Private final sharedpreferences cookieprefs;        Public Persistentcookiestore (Context context) {cookieprefs = context.getsharedpreferences (cookie_prefs, 0);        cookies = new hashmap<string, concurrenthashmap<string, cookie>> ();        Cache persistent cookies in memory as Map cookies map<string,?> prefsmap = Cookieprefs.getall (); For (map.entry<string,?> entry:prefsMap.entrySet ()) {string[] Cookienames = Textutils.split ((String)            Entry.getvalue (), ",");                for (string name:cookienames) {string encodedcookie = cookieprefs.getstring (name, NULL);        if (Encodedcookie! = null) {Cookie Decodedcookie = Decodecookie (Encodedcookie);            if (Decodedcookie! = null) {if (!cookies.containskey (Entry.getkey ())) {                        Cookies.put (Entry.getkey (), New concurrenthashmap<string, cookie> ());                    } cookies.get (Entry.getkey ()). Put (name, Decodedcookie); }}}}} protected String Getcookietoken (cookie cookie) {return Cookie.nam    E () + "@" + cookie.domain ();        } public void Add (httpurl url, cookie cookie) {String name = Getcookietoken (cookie);                Cache cookies in memory if the cache expires, reset this cookie if (!cookie.persistent ()) {if (!cookies.containskey (Url.host ())) {            Cookies.put (Url.host (), New concurrenthashmap<string, cookie> ());        } cookies.get (Url.host ()). Put (name, cookie);            } else {if (Cookies.containskey (Url.host ())) {Cookies.get (Url.host ()). Remove (name);     }   }//Tell the cookie to persist to local sharedpreferences.editor Prefswriter = Cookieprefs.edit ();        Prefswriter.putstring (Url.host (), Textutils.join (",", Cookies.get (Url.host ()). KeySet ());        Prefswriter.putstring (Name, Encodecookie (new Serializableokhttpcookies (cookie)));    Prefswriter.apply ();        } public list<cookie> get (httpurl URL) {arraylist<cookie> ret = new arraylist<cookie> ();        if (Cookies.containskey (Url.host ())) Ret.addall (Cookies.get (Url.host ())). values ());    return ret;        } public boolean RemoveAll () {Sharedpreferences.editor prefswriter = Cookieprefs.edit ();        Prefswriter.clear ();        Prefswriter.apply ();        Cookies.clear ();    return true;        } public boolean remove (httpurl URL, cookie cookie) {String name = Getcookietoken (cookie); if (Cookies.containskey (Url.host ()) && Cookies.get (Url.host ()). ContainsKey (name)) {Cookies.get (Url.hos T ()). Remove (nAME);            Sharedpreferences.editor prefswriter = Cookieprefs.edit ();            if (cookieprefs.contains (name)) {prefswriter.remove (name);            } prefswriter.putstring (Url.host (), Textutils.join (",", Cookies.get (Url.host ()). KeySet ());            Prefswriter.apply ();        return true;        } else {return false;        }} public list<cookie> getcookies () {arraylist<cookie> ret = new arraylist<cookie> ();        For (String Key:cookies.keySet ()) Ret.addall (Cookies.get (key). values ());    return ret; }/** * Cookies are serialized into a string * * @param cookies to serialize Cookies * @return Serialized String */protected St        Ring Encodecookie (Serializableokhttpcookies cookie) {if (cookie = = null) return null;        Bytearrayoutputstream OS = new Bytearrayoutputstream ();           try {objectoutputstream outputstream = new ObjectOutputStream (OS); Outputstream.writeobject (cookie);            } catch (IOException e) {log.d (Log_tag, "IOException in Encodecookie", e);        return null;    } return Bytearraytohexstring (Os.tobytearray ()); }/** * Deserializes strings into cookies * * @param cookiestring Cookies String * @return Cookie Object */Prote        CTED Cookie Decodecookie (String cookiestring) {byte[] bytes = Hexstringtobytearray (cookiestring);        Bytearrayinputstream Bytearrayinputstream = new Bytearrayinputstream (bytes);        Cookie cookie = null;            try {objectinputstream ObjectInputStream = new ObjectInputStream (bytearrayinputstream);        Cookie = ((serializableokhttpcookies) Objectinputstream.readobject ()). GetCookies ();        } catch (IOException e) {log.d (Log_tag, "IOException in Decodecookie", e);        } catch (ClassNotFoundException e) {log.d (Log_tag, "classnotfoundexception in Decodecookie", e); } return CookiE }/** binary array to hexadecimal string * * @param bytes byte array to be converted * @return string containing hex value  S */protected String bytearraytohexstring (byte[] bytes) {StringBuilder sb = new StringBuilder (bytes.length        * 2);            for (byte element:bytes) {int v = element & 0xFF;            if (v <) {Sb.append (' 0 ');        } sb.append (Integer.tohexstring (v));    } return Sb.tostring (). toUpperCase (locale.us);     }/** * Hex string to binary array * * @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), +) <<        4) + character.digit (Hexstring.charat (i + 1), 16));    } return data; }}
public class Serializableokhttpcookies implements Serializable {private transient final Cookie cookies;    private transient Cookie clientcookies;    Public serializableokhttpcookies (Cookie cookies) {this.cookies = cookies;        } public Cookie GetCookies () {Cookie bestcookies = cookies;        if (clientcookies! = null) {bestcookies = clientcookies;    } return bestcookies;        } private void WriteObject (ObjectOutputStream out) throws IOException {Out.writeobject (Cookies.name ());        Out.writeobject (Cookies.value ());        Out.writelong (Cookies.expiresat ());        Out.writeobject (Cookies.domain ());        Out.writeobject (Cookies.path ());        Out.writeboolean (Cookies.secure ());        Out.writeboolean (Cookies.httponly ());        Out.writeboolean (Cookies.hostonly ());    Out.writeboolean (Cookies.persistent ()); private void ReadObject (ObjectInputStream in) throws IOException, classnotfoundexception {String nAme = (String) in.readobject ();        String value = (string) in.readobject ();        Long Expiresat = In.readlong ();        String domain = (string) in.readobject ();        String path = (string) in.readobject ();        Boolean secure = In.readboolean ();        Boolean httponly = In.readboolean ();        Boolean hostonly = In.readboolean ();        Boolean persistent = In.readboolean ();        Cookie.builder Builder = new Cookie.builder ();        Builder = builder.name (name);        Builder = Builder.value (value);        Builder = Builder.expiresat (Expiresat); Builder = hostonly?        Builder.hostonlydomain (domain): builder.domain (domain);        Builder = Builder.path (path); Builder = secure?        Builder.secure (): builder; Builder = HttpOnly?        Builder.httponly (): builder;    Clientcookies =builder.build (); }}


I don't know how to comment.


OKHTTP3 's use, the actual combat experience of their own projects

Contact Us

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.