OKHTTPokHttp:Okhttp is an Android version of the HTTP client. Very efficient, supports spdy, connection pooling, gzip, and HTTP caching. By default, Okhttp automatically handles common network problems, such as two-connection, SSL handshake issues. If you have integrated Okhttp,retrofit in your application, the default is to use Okhttp to handle other network layer requests.
An HTTP & SPDY client for Android and Java applications
The underlying implementation of HttpURLConnection starting with Android4.4 is okhttp.
Usage requirements: For android:2.3 above, for Java:java7 above two modules:okhttp-urlconnection implementation . HttpURLConnection API; Okhttp-apache implements the Apache HttpClient API. Depend on:
Okio(Https://github.com/square/okio): Okio, which OkHttp uses for fast I/O and resizable buffers. Installation: Maven:
<dependency> <groupId>com.squareup.okhttp</groupId> <artifactid>okhttp</ Artifactid> <version>2.3.0</version></dependency>
Gradle:
Compile ' com.squareup.okhttp:okhttp:2.3.0 '
Get A URL synchronization get:
Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception { Request request = new Request.builder () . URL ("http://publicobject.com/ Helloworld.txt ") . Build (); Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); Headers responseheaders = Response.headers (); for (int i = 0; i < responseheaders.size (); i++) { System.out.println (responseheaders.name (i) + ":" + responsehead Ers.value (i)); } System.out.println (Response.body (). String ());
Asynchronous get: A file is downloaded in a worker thread, and the callback interface is recalled when the response is readable. The current thread is blocked when the response is read. Okhttp does not provide an asynchronous API to receive the response body at this stage.
Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception { Request request = new Request.builder () . URL ("http://publicobject.com/ Helloworld.txt ") . Build (); Client.newcall (Request) Enqueue (new Callback () { @Override public void onfailure (Request request, Throwable Throwable) { throwable.printstacktrace (); } @Override public void Onresponse (Response Response) throws IOException { if (!response.issuccessful ()) throw new IOE Xception ("Unexpected Code" + response); Headers responseheaders = Response.headers (); for (int i = 0; i < responseheaders.size (); i++) { System.out.println (responseheaders.name (i) + ":" + Responsehea Ders.value (i)); } System.out.println (Response.body (). String ());}} );
To access the header:
Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception { Request request = new Request.builder () . URL ("Https://api.github.com/repos /square/okhttp/issues ") . Header (" User-agent "," Okhttp Headers.java ") . AddHeader (" Accept "," application/ Json q=0.5 ") . AddHeader (" Accept "," Application/vnd.github.v3+json ") . Build (); Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); SYSTEM.OUT.PRINTLN ("server:" + response.header ("server")); System.out.println ("Date:" + Response.header ("date")); System.out.println ("Vary:" + response.headers ("Vary")); }
POST to a serverposting a String:
public static final mediatype jsonreq = Mediatype.parse ("Application/json; Charset=utf-8 "); Okhttpclient client = new Okhttpclient (); String post (string URL, string json) throws IOException { Requestbody BODY = requestbody.create (jsonreq, JSON); Request Request = new Request.builder () . URL (URL). post (body) . Build (); Response Response = client.newcall (Request). Execute (); Return Response.body (). String ();}
Posting Streaming:
public static final MediaType Media_type_markdown = Mediatype.parse ("Text/x-markdown; Charset=utf-8 "); Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception {requestbody requestbody = new Requestbody () {@Override Public mediatype cont Enttype () {return media_type_markdown; } @Override public void WriteTo (Bufferedsink sink) throws IOException {Sink.writeutf8 ("numbers\n"); Sink.writeutf8 ("-------\ n"); for (int i = 2; I <= 997; i++) {Sink.writeutf8 (String.Format ("*%s =%s\n", I, Factor (i))); }} private String factor (int n) {for (int i = 2; i < n; i++) {int x = n/i; if (x * i = = N) return factor (x) + "x" + i; } return integer.tostring (n); } }; Request Request = new Request.builder (). URL ("Https://api.github.com/markdown/raw"). Post (Requestbody) . build (); Response Response = client.neWcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); System.out.println (Response.body (). String ()); }
Posting a File:
public static final mediatype Media_type_markdown = Mediatype.parse ("Text/x-markdown; Charset=utf-8 "); Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception { file File = new file ("Readme.md"); Request Request = new Request.builder () . URL ("Https://api.github.com/markdown/raw") . Post ( Requestbody.create (Media_type_markdown, file)) . Build (); Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); System.out.println (Response.body (). String ());
Posting from Parameters:
Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception { requestbody formbody = new Formencodingbuilder () . Add ("Search", "Jurassic Pa RK ") . Build (); Request Request = new Request.builder () . URL ("https://en.wikipedia.org/w/index.php") . Post (Formbody) . Build (); Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); System.out.println (Response.body (). String ());
Posting a multipart request:
private static final String imgur_client_id = "..."; Private static final mediatype media_type_png = Mediatype.parse ("Image/png"); Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception {//with the Imgur image upload API as documented at https://api.imgur.com/endpoints /image requestbody requestbody = new Multipartbuilder (). Type (Multipartbuilder.form). Addpart ( Headers.of ("Content-disposition", "form-data; Name=\ "Title\"), Requestbody.create (null, "Square Logo")). Addpart (Headers.of ("Content-disp Osition "," form-data; Name=\ "image\"), Requestbody.create (Media_type_png, New File ("Website/static/logo-square.png")). Build (); Request Request = new Request.builder (). Header ("Authorization", "Client-id" + imgur_client_id). URL ("https ://api.imgur.com/3/image "). Post (Requestbody). build (); Response Response = client.newcall (request). executE (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); System.out.println (Response.body (). String ()); }
Posing Json with Gson
Private final Okhttpclient client = new Okhttpclient (); Private final Gson Gson = new Gson (); public void Run () throws Exception { Request request = new Request.builder () . URL ("https://api.github.com/gists /c2a7c39532239ff261be ") . Build (); Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); Gist Gist = Gson.fromjson (Response.body (). Charstream (), gist.class); For (map.entry<string, gistfile> entry:gist.files.entrySet ()) { System.out.println (Entry.getkey ()); System.out.println (Entry.getvalue (). content); } } Static class Gist { map<string, gistfile> files; } Static class Gistfile { String content; }
Response Caching: In order to cache the response, you need a cache directory that you can read and write, and a limit on the size of the cache. This cache directory should be private and untrusted programs should not be able to read the cached content.
It is an error to have multiple cache accesses for a cache directory at the same time. Most programs only need to call new OkHttp () once, configure the cache on the first call, and then just call this instance elsewhere. Otherwise two cache samples interfere with each other, destroy the response cache, and may cause the program to crash.
The response cache uses HTTP headers as the configuration. You can add cache-control:max-stale=3600 to the request header, and the Okhttp cache will support it. Your service determines how long the response is cached through the response header, such as using cache-control:max-age=9600.
Private final okhttpclient client; Public Cacheresponse (File cachedirectory) throws Exception { int cacheSize = ten * 1024x768 *;//MiB Cache CAC he = new Cache (cachedirectory, cacheSize); Client = new Okhttpclient (); Client.setcache (cache); } public void Run () throws Exception { Request request = new Request.builder () . URL ("http://publicobject.com/ Helloworld.txt ") . Build (); Response response1 = client.newcall (Request). Execute (); if (!response1.issuccessful ()) throw new IOException ("Unexpected Code" + response1); String response1body = Response1.body (). String (); System.out.println ("Response 1 Response: " + response1); System.out.println ("Response 1 cache Response: " + response1.cacheresponse ()); System.out.println ("Response 1 network Response: " + response1.networkresponse ()); }
Canceling a call
Final Call call = Client.newcall (request); Call.cancel ();
Timeouts:
Private final okhttpclient client; Public configuretimeouts () throws Exception { client = new Okhttpclient (); Client.setconnecttimeout (ten, timeunit.seconds); Client.setwritetimeout (ten, timeunit.seconds); Client.setreadtimeout (timeunit.seconds); }
Handling Authentication:
Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception {Client.setauthenticator (new Authenticator () {@Override public Request Authen Ticate (proxy proxy, Response Response) {System.out.println ("Authenticating for Response:" + Response); System.out.println ("Challenges:" + response.challenges ()); String credential = Credentials.basic ("Jesse", "Password1"); Return Response.request (). Newbuilder () header ("Authorization", credential). Build (); } @Override Public Request authenticateproxy (proxy proxy, Response Response) {return null;//NULL indicates No attempt to authenticate. } }); Request Request = new Request.builder (). URL ("Http://publicobject.com/secrets/hellosecret.txt"). Build (); Response Response = client.newcall (Request). Execute (); if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response); System.out.println (Response.body (). String ()); }
To avoid multiple retries when validation fails, we can discard the validation by returning NULL:
if (Responsecount (response) >= 3) { return null;//If we ' ve failed 3 times, give up. } Add the following method to private int responsecount (Response Response) { int result = 1; while ((response = Response.priorresponse ()) = null) { result++; } return result; }
Interceptors
Class Logginginterceptor implements Interceptor { @Override public Response intercept (Chain Chain) throws IOException { Request request = Chain.request (); Long T1 = System.nanotime (); Logger.info (String.Format ("Sending request%s on%s%n%s", Request.url (), Chain.connection (), Request.headers ()) ); Response Response = chain.proceed (request); Long t2 = System.nanotime (); Logger.info (String.Format ("Received response for%s in%.1fms%n%s", response.request (). URL (), (T2-T1)/1e6d, RESP Onse.headers ())); return response;} }
Application interceptors:
Okhttpclient client = new Okhttpclient (); Client.interceptors (). Add (New Logginginterceptor ());
Network Interceptors
Okhttpclient client = new Okhttpclient (); Client.networkinterceptors (). Add (New Logginginterceptor ());
Android Network Framework Learning Okhttp