Okhttp Introduction to use

Source: Internet
Author: User

Now Android network aspects of the third-party library, Volley,retrofit,okhttp, and so on, each has its own characteristics, this blog will be a brief introduction to how to use the okhttp.

Outline

Okhttp is an efficient HTTP client that supports links to the same address to share the same socket, to reduce response latency through connection pooling, as well as transparent gzip compression, request caching and other benefits Okhttp official website

Configuring the Environment

Supports Android 2.3 and above, requires more than Java JDK1.7

Jar Package Introduction

You can import the project address directly by downloading the jar package as follows
or by building a way to import
Maven:

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

GRADLE

‘com.squareup.okhttp:okhttp:2.4.0‘
Usage

When you make a request to the network, the most common thing we use is get and post, let's see how
1. GET
In Okhttp, every time a network request is requested, we fill in request with other parameters such as the url,header we need, and then through request constructs the Call,call internal to ask for parameters, get a reply, and tell the caller the result.

 PackageCom.jackchan.test.okhttptest;ImportAndroid.os.Bundle;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.util.Log;ImportCom.squareup.okhttp.Cache;ImportCom.squareup.okhttp.Callback;ImportCom.squareup.okhttp.OkHttpClient;ImportCom.squareup.okhttp.Request;ImportCom.squareup.okhttp.Response;ImportJava.io.File;ImportJava.io.IOException; Public  class testactivity extends actionbaractivity {    Private Final StaticString TAG ="Testactivity";Private FinalOkhttpclient client =NewOkhttpclient ();@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (r.layout.activity_test);NewThread (NewRunnable () {@Override             Public void Run() {Try{Execute (); }Catch(Exception e)                {E.printstacktrace ();    }}). Start (); } Public void Execute()throwsException {Request Request =NewRequest.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 the Request.builder incoming URL, and then execute executes directly to get response, through response can get code,message and other information.

This is a synchronous way to operate the network request, and Android itself is not allowed to do the Web request operation on the UI thread, so we need to open a thread ourselves.

Of course, Okhttp also supports asynchronous threads and has callbacks to return, with the basis of synchronization above, asynchronous as long as a slight change can

Private void Enqueue() {Request request =NewRequest.builder (). URL ("Http://publicobject.com/helloworld.txt"). build (); Client.newcall (Request). Enqueue (NewCallback () {@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());    }            }        }); }

It is on a synchronous basis that execute is changed to Enqueue, and the callback interface is passed in, but the interface callback code is in the non-UI thread, so if there is an update UI operation remember to use handler or other means.

2. POST

said get the introduction of how to use the Post,post case we generally need to pass in parameters, even some headers, incoming parameters or headers
such as incoming header
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 final call is the same as the Get method

Responseresponse = client.newCall(request).execute();    if (response.isSuccessful()) {        response.body().string();    else {        new IOException("Unexpected code "response);    }

This code is synchronous network request, asynchronous change to enqueue on the line.

Simple for the use of okhttp introduced here, the next focus from the source point of view on how the whole okhttp is working.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Okhttp Introduction to use

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.