Android uses the OKHTTP packet to handle the basic usage of HTTP-related operations explain _android

Source: Internet
Author: User
Tags connection pooling

Okhttp is an efficient HTTP client that supports links to the same address sharing the same socket, reducing response latency through connection pooling, and transparent gzip compression, request caching, and more. (GitHub page: https://github.com/square/okhttp)

Android provides us with two ways of HTTP interaction: HttpURLConnection and Apache http Client, although both support HTTPS, streaming uploads and downloads, configuration timeouts, IPv6 and connection pooling, is sufficient to meet the requirements of our various HTTP requests. But more efficient use of HTTP can make your application run faster and save more traffic. And the Okhttp library was born for that.
Okhttp is an efficient HTTP library:

    • Supports SPDY, sharing the same socket to handle all requests for the same server
    • Reduce request latency through connection pooling if Spdy is not available
    • Seamless support for gzip to reduce data traffic
    • Cache response data to reduce duplicate network requests
    • Automatically recovers from many common connection problems.

If your server is configured with multiple IP addresses, Okhttp will automatically try the next IP when the first IP connection fails. Okhttp also handles the proxy server problem and the SSL handshake failure issue.
Using okhttp eliminates the need to rewrite the network code in your program. Okhttp implements almost the same API as Java.net.HttpURLConnection. If you use Apache httpclient, Okhttp also provides a corresponding Okhttp-apache module.


introduced
You can import the project address directly by downloading the jar package
Or you can import it in a structured way
Maven:

<dependency>
 <groupId>com.squareup.okhttp</groupId>
 <artifactid>okhttp</ artifactid>
 <version>2.4.0</version>
</dependency>

Gradle:

Compile ' com.squareup.okhttp:okhttp:2.4.0 '

Usage
when we make a request to the Web, the most common is get and post, and here's how to use
1. Get
in Okhttp, every time a network request is a petition, we fill in the request with the Url,header and other parameters we need, and then construct the call,call inside to request parameters, get a reply, and tell the caller the result.
Package com.jackchan.test.okhttptest;
Import Android.os.Bundle;
Import android.support.v7.app.ActionBarActivity;
Import Android.util.Log;
Import Com.squareup.okhttp.Cache;
Import Com.squareup.okhttp.Callback;
Import com.squareup.okhttp.OkHttpClient;
Import Com.squareup.okhttp.Request;
Import Com.squareup.okhttp.Response;
Import Java.io.File;
Import java.io.IOException;
  public class Testactivity extends Actionbaractivity {private final static String TAG = "testactivity";
  Private final Okhttpclient client = new Okhttpclient ();
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_test);
        New Thread (New Runnable () {@Override public void run () {try {execute ());
        catch (Exception e) {e.printstacktrace ();
  }}). Start (); The public void execute () throws Exception {Request request = new Request.builder (). URL ("hTtp://publicobject.com/helloworld.txt "). Build ();
    Response Response = client.newcall (Request). Execute ();
      if (response.issuccessful ()) {System.out.println (Response.code ());
    System.out.println (Response.body (). String ());
 }
  }
}
We pass request.builder to the URL, and then execute directly execute to get response, through response can get code,message information.
This is done synchronously to operate the network request, and Android itself is not allowed to do the network request operation on the UI thread, so we need to open a thread ourselves.
Of course, Okhttp also supports asynchronous threads and has callback returns, with the basis of the above synchronization, asynchronous as long as a slight change can
private void Enqueue () {
    Request request = new Request.builder ()
        . URL ("Http://publicobject.com/helloworld.txt ")
        . Build ();
    Client.newcall (Request). Enqueue (New Callback () {
      @Override public
      void OnFailure (Request request, IOException e) {
      }
      @Override public
      void Onresponse (Response Response) throws IOException {
        //not UI Thread
        if (response.issuccessful ()) {
          System.out.println (Response.code ());
          System.out.println (Response.body (). String ());}}}
  
On the basis of synchronization, execute is changed to Enqueue, and the callback interface is passed in, but the interface callback code is in a non-UI thread, so if there is an action to update the UI, remember to use handler or some other way.
2, POST
finish saying get this describes how to use the Post,post case we generally need to pass in parameters, even some header, incoming parameter or header
Like incoming headers.
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 (); 
Incoming Post Parameters
Requestbody formbody = new Formencodingbuilder ()
  . Add ("Platform", "Android")
  . Add ("name", "Bug").
  Add ( "Subject", "xxxxxxxxxxxxxxx")
  . Build ();
  Request Request = new Request.builder ()
   . URL (URL)
   . Post (body). Build
   ();
As you can see, the incoming header or post parameters are uploaded to the request, so the last call is the same as the Get way
Response Response = client.newcall (Request). Execute ();
  if (response.issuccessful ()) {return
    response.body (). String ();
  } else {
    throw new IOException (" Unexpected code "+ response);
  }
This code is synchronous network request, the asynchronous is changed to Enqueue on the line.

Request caching
in the network request, caching technology is a widely used technology, need to cache the requested network resources, and Okhttp also support this technology, also very convenient to use, the previous okhttpclient often appear in this time will be used. Look at the code below.
Package com.jackchan.test.okhttptest;
Import Android.os.Bundle;
Import android.support.v7.app.ActionBarActivity;
Import Android.util.Log;
Import Com.squareup.okhttp.Cache;
Import Com.squareup.okhttp.CacheControl;
Import Com.squareup.okhttp.Call;
Import Com.squareup.okhttp.Callback;
Import com.squareup.okhttp.OkHttpClient;
Import Com.squareup.okhttp.Request;
Import Com.squareup.okhttp.Response;
Import Java.io.File;
Import java.io.IOException;
  public class Testactivity extends Actionbaractivity {private final static String TAG = "testactivity";
  Private final Okhttpclient client = new Okhttpclient ();
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_test);
    File Sdcache = Getexternalcachedir (); int cacheSize = 10 * 1024 * 1024;
    A MiB Client.setcache (new Cache (Sdcache.getabsolutefile (), cacheSize));
    New Thread (New Runnable () {@Override public void run () {    try {execute ();
        catch (Exception e) {e.printstacktrace ();
  }}). Start (); The public void execute () 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 ());
    Response Response2 = client.newcall (Request). Execute ();
    if (!response2.issuccessful ()) throw new IOException ("Unexpected Code" + Response2);
    String response2body = Response2.body (). String (); System.out.println ("Response 2 Response:" + response2);
    System.out.println ("Response 2 cache Response:" + response2.cacheresponse ());
    System.out.println ("Response 2 network Response:" + response2.networkresponse ());
  System.out.println ("Response 2 equals Response 1" + response1body.equals (response2body));
 }
}
Okhttpclient a bit like the concept of application, co-ordinating the entire okhttp of the large function, through it to set the cache directory, we execute the above code, the results are as follows
The result of Response1 in Networkresponse, the representative is loaded from the network request, and RESPONSE2 networkresponse is null, and Cacheresponse has data, Because I set up the cache so the second request found that there is no longer go to the network request in the cache.
But sometimes even in the case of caching we still need to go backstage to request the latest resources (such as resource updates), this time you can use a forced-GO network to request network data
 public void execute () throws Exception {Request request = new Request.builder (). URL ("http://publicobject.c
    Om/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 ());
    Request = Request.newbuilder (). CacheControl (Cachecontrol.force_network). build ();
    Response Response2 = client.newcall (Request). Execute ();
    if (!response2.issuccessful ()) throw new IOException ("Unexpected Code" + Response2);
    String response2body = Response2.body (). String ();
    System.out.println ("Response 2 Response:" + response2); System.out.println ("Response 2 cache RespoNSE: "+ response2.cacheresponse ());
    System.out.println ("Response 2 network Response:" + response2.networkresponse ());
  System.out.println ("Response 2 equals Response 1" + response1body.equals (response2body));
 }
In the code above
Response2 corresponding request to become
Request = Request.newbuilder (). CacheControl (Cachecontrol.force_network). build ();
Let's look at the running results.
RESPONSE2 Cache response for null,network response still have data.
Similarly, we can use Force_cache to force only the use of cached data, but if the request must be obtained from the network to have data, but also use the Force_cache policy will return 504 error, the code is as follows, we go to okhttpclient cache, and set request to Force_cache
protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_test);
    File Sdcache = Getexternalcachedir (); int cacheSize = 10 * 1024 * 1024;
    A MiB//client.setcache (new Cache (Sdcache.getabsolutefile (), cacheSize));
        New Thread (New Runnable () {@Override public void run () {try {execute ());
          catch (Exception e) {e.printstacktrace ();
        System.out.println (E.getmessage (). toString ());
  }}). Start (); The public void execute () 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 ());
    Request = Request.newbuilder (). CacheControl (Cachecontrol.force_cache). build ();
    Response Response2 = client.newcall (Request). Execute ();
    if (!response2.issuccessful ()) throw new IOException ("Unexpected Code" + Response2);
    String response2body = Response2.body (). String ();
    System.out.println ("Response 2 Response:" + response2);
    System.out.println ("Response 2 cache Response:" + response2.cacheresponse ());
    System.out.println ("Response 2 network Response:" + response2.networkresponse ());
  System.out.println ("Response 2 equals Response 1" + response1body.equals (response2body));
 }
Cancel operation
in network operations, the cancel operation of the request is often used, and okhttp also provides this interface, call cancel operation. Use Call.cancel () to immediately stop a call that is executing. If a thread is writing a request or reading a response, a ioexception will be raised, and a label can be set by Request.Builder.tag (Object tag) to the request, using the Okhttpclient.cancel object Tag) to cancel all call with this tag. However, if the request is already in a read-write operation, Cancel cannot succeed and throws a IOException exception.
public void Canceltest () throws Exception {Request request = new Request.builder (). URL ("http://httpbin.org/
        DELAY/2 ")//This URL was served with a 2 second delay.
    . build ();
    Final Long Startnanos = System.nanotime ();
    Final Call call = Client.newcall (request);
    Schedule a job to cancel the call in 1 second. Executor.schedule (New Runnable () {@Override public void run () {System.out.printf ("%.2f canceling cal
        L.%n ", (System.nanotime ()-Startnanos)/1e9f);
        Call.cancel ();
      System.out.printf ("%.2f Canceled call.%n", (System.nanotime ()-Startnanos)/1e9f);
    }, 1, timeunit.seconds);
      try {System.out.printf ("%.2f Executing call.%n", (System.nanotime ()-Startnanos)/1e9f);
      Response Response = Call.execute ();
      SYSTEM.OUT.PRINTF ("Call is Cancel:" + call.iscanceled () + "%n"); System.out.printf ("%.2f call is expected to fail, but completed:%s%n", (System.nanotime ()-StarTnanos)/1e9f, response); catch (IOException e) {System.out.printf ("%.2f call failed as expected:%s%n", (System.nanotime ()-STA
    Rtnanos)/1e9f, E);
 }
  }
Successfully canceled
Cancel failed
Related Article

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.