Android network communication okHttp

Source: Internet
Author: User

Okhttp is a Java http+spdy client development package and also supports Android. Requires Android 2.3 or more.

Characteristics
    • 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.
    • The underlying implementation of HttpURLConnection starting with Android4.4 is okhttp.
    • Sync: Send HTTP request → get return results → analysis results → jump to next page
      Async: Send http request → Jump to next page (no waiting for request result, processing of result in another thread)

      If the synchronization of the words will be stuck to the UI interface,
      Android4.1 is not allowed to use sync requests later.
Usage
    1. Create a new Okhttpclient object
    2. Create a new Request object from the Request.builder object
    3. Return to execution results

      • GET
private string get (string url) {        okhttpclient client = new Okhttpclient ();        Request Request = new Request.builder ()                . URL (URL)                . Build ();        Response Response = null;        try {            response = Client.newcall (Request). Execute ();            Return Response.body (). String ();        } catch (IOException e) {            e.printstacktrace ();        }        return null;    }

    • POST

Post needs to use the Requestbody object, and then call the post function to pass it in when building the request object.

private string post (string url) {        okhttpclient client = new Okhttpclient ();        Requestbody formbody = new Formencodingbuilder (). Add ("                user", "Jurassic Park"). Add                ("Pass", "Asasa").                add ("Time", "12132")                . Build ();        Request Request = new Request.builder ()                . URL (URL).                post (formbody)                . Build ();        Response Response = null;        try {            response = Client.newcall (Request). Execute ();            Return Response.body (). String ();        } catch (IOException e) {            e.printstacktrace ();        }        return null;    }

In addition, the use of the Post method also supports the operation of the file, the specific use of interested can be self-access

    • Support for the Gson

Okhttp also has his own support for Gson.

  Private person Gson (String url) {        okhttpclient client = new Okhttpclient ();        Gson Gson = new Gson ();        Request Request = new Request.builder ()                . URL (URL)                . Build ();        Response Response = null;        try {            response = Client.newcall (Request). Execute ();            Person person = Gson.fromjson (Response.body (). Charstream (), person.class);            return person;        } catch (IOException e) {            e.printstacktrace ();        }        return null;    }

    • Asynchronous operation

The above two examples must be done in a child thread, and Okhttp also provides an asynchronous method call, which is made by using a callback to make an asynchronous call, and then the okhttp callback is still not in the main thread, so the UI cannot be manipulated in the callback

private void Getasync (String url) {        okhttpclient client = new Okhttpclient ();        Request Request = new Request.builder ()                . URL (URL)                . Build ();        Response Response = null;        Client.newcall (Request) Enqueue (new Callback () {            @Override public            void OnFailure (Request request, IOException e) {            }            @Override public            void Onresponse (Response Response) throws IOException {                String result = Response.body (). String ();                Toast.maketext (Getapplicationcontext (), Result,toast.length_short). Show ();                Unable to manipulate UI, callback is still in child thread                log.d ("TAG", result);}        );    }

Http://www.open-open.com/lib/view/open1435381866122.html

Android network communication okHttp

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.