Use of Okhttp

Source: Internet
Author: User
Tags getmessage html file upload oauth

Download OKHTTP3
implementation ‘com.squareup.okhttp3:okhttp:3.10.0‘
1.1. Asynchronous GET Requests

-new okhttpclient;
-Construct the Request object;
-Build call objects from the objects in the first two steps;
-Submit an asynchronous request via the Call#enqueue (Callback) method;

String url = "http://wwww.baidu.com";OkHttpClient okHttpClient = new OkHttpClient();final Request request = new Request.Builder()        .url(url)        .get()//默认就是GET请求,可以不写        .build();Call call = okHttpClient.newCall(request);call.enqueue(new Callback() {    @Override    public void onFailure(Call call, IOException e) {        Log.d(TAG, "onFailure: ");    }    @Override    public void onResponse(Call call, Response response) throws IOException {        Log.d(TAG, "onResponse: " + response.body().string());    }});

Asynchronously initiated requests are added to Dispatcher the runningAsyncCalls double-ended queue in the thread pool to execute.

1.2. Synchronizing GET Requests

The first few steps are the same as asynchronous, except that the last is Call#execute() to commit the request, and notice that it blocks the calling thread, so it should be executed in the child thread on Android, otherwise it might cause a ANR exception that is Android3.0 not allowed to access the network in the main thread.

String url = "http://wwww.baidu.com";OkHttpClient okHttpClient = new OkHttpClient();final Request request = new Request.Builder()        .url(url)        .build();final Call call = okHttpClient.newCall(request);new Thread(new Runnable() {    @Override    public void run() {        try {            Response response = call.execute();            Log.d(TAG, "run: " + response.body().string());        } catch (IOException e) {            e.printStackTrace();        }    }}).start();
2.1. Post method Submission string

The difference between this approach and the previous one is that when constructing the request object, you need to construct a Requestbody object that carries the data we want to submit. In the construction needs to be RequestBody specified MediaType , the content type used to describe the request/response body , MediaType more information about the RFC 2045 can be viewed

Request_body

MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");String requestBody = "I am Jdqm.";Request request = new Request.Builder()        .url("https://api.github.com/markdown/raw")        .post(RequestBody.create(mediaType, requestBody))        .build();OkHttpClient okHttpClient = new OkHttpClient();okHttpClient.newCall(request).enqueue(new Callback() {    @Override    public void onFailure(Call call, IOException e) {        Log.d(TAG, "onFailure: " + e.getMessage());    }    @Override    public void onResponse(Call call, Response response) throws IOException {        Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());        Headers headers = response.headers();        for (int i = 0; i < headers.size(); i++) {            Log.d(TAG, headers.name(i) + ":" + headers.value(i));        }        Log.d(TAG, "onResponse: " + response.body().string());    }});

Response Content

http/1.1 200 OK Date:Sat, 10 Mar 2018 05:23:20 GMT Content-Type:text/html;charset=utf-8Content-Length:18Server:GitHub.com Status:200 OK X-RateLimit-Limit:60X-RateLimit-Remaining:52X-RateLimit-Reset:1520661052X-CommonMarker-Version:0.17.4Access-Control-Expose-Headers:ETag, Link, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-IntervalAccess-Control-Allow-Origin:*Content-Security-Policy:default-src ‘none‘Strict-Transport-Security:max-age=31536000; includeSubdomains; preload X-Content-Type-Options:nosniff X-Frame-Options:deny X-XSS-Protection:1; mode=block X-Runtime-rack:0.019668Vary:Accept-Encoding X-GitHub-Request-Id:1474:20A83:5CC0B6:7A7C1B:5AA36BC8 onResponse: <p>I am Jdqm.</p>
2.2 Post mode for AC
Requestbody requestbody = new Requestbody () {@Nullable @Override public mediatype ContentType () {return Mediatype.parse ("Text/x-markdown;    Charset=utf-8 ");    } @Override public void WriteTo (Bufferedsink sink) throws IOException {Sink.writeutf8 ("I am jdqm."); }};        Request Request = new Request.builder (). URL ("Https://api.github.com/markdown/raw"). Post (Requestbody) . build (); Okhttpclient okhttpclient = new Okhttpclient (); Okhttpclient.newcall (Request). Enqueue (New Callback () {@Overr    IDE public void OnFailure (call call, IOException e) {log.d (TAG, "onfailure:" + e.getmessage ()); } @Override public void Onresponse (call call, Response Response) throws IOException {log.d (TAG, Response.pro        Tocol () + "+response.code () +" "+ response.message ());        Headers Headers = Response.headers ();    for (int i = 0; i < headers.size (); i++) {log.d (TAG, Headers.name (i) + ":" + headers.value (i));    } log.d (TAG, "onresponse:" + response.body (). String ()); }});
2.3. Post Submission File
MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");OkHttpClient okHttpClient = new OkHttpClient();File file = new File("test.md");Request request = new Request.Builder()        .url("https://api.github.com/markdown/raw")        .post(RequestBody.create(mediaType, file))        .build();okHttpClient.newCall(request).enqueue(new Callback() {    @Override    public void onFailure(Call call, IOException e) {        Log.d(TAG, "onFailure: " + e.getMessage());    }    @Override    public void onResponse(Call call, Response response) throws IOException {        Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());        Headers headers = response.headers();        for (int i = 0; i < headers.size(); i++) {            Log.d(TAG, headers.name(i) + ":" + headers.value(i));        }        Log.d(TAG, "onResponse: " + response.body().string());    }});
2.4. Post method Submission Form
  okhttpclient okhttpclient = new Okhttpclient (); Requestbody requestbody = new Formbody.builder (). Add ("Search", "Jurassic Park"). Build ();        Request Request = new Request.builder (). URL ("https://en.wikipedia.org/w/index.php"). Post (Requestbody) . build (); Okhttpclient.newcall (Request) Enqueue (new Callback () {@Override public void onfailure, IOEXCE    Ption e) {log.d (TAG, "onfailure:" + e.getmessage ()); } @Override public void Onresponse (call call, Response Response) throws IOException {log.d (TAG, Response.pro        Tocol () + "+response.code () +" "+ response.message ());        Headers Headers = Response.headers ();        for (int i = 0; i < headers.size (); i++) {log.d (TAG, Headers.name (i) + ":" + headers.value (i));    } log.d (TAG, "onresponse:" + response.body (). String ()); }});

When a form is submitted, RequestBody the implementation class is used FormBody to describe the request body, which can carry a number of encoded key-value request bodies, and key-value pairs are stored in the following two collections:

  private final List<String> encodedNames;  private final List<String> encodedValues;
2.5. Post way to submit chunked requests

Multipartbody can build complex request bodies that are compatible with the HTML file upload format. Each request in a multiple-block request body is a request body that can define its own request header. These request headers can be used to describe the request, such as its Content-Disposition . If Content-Length and when Content-Type available, they are automatically added to the request header.

private static final String imgur_client_id = "...";P rivate static final mediatype media_type_png = Mediatype.parse ("image    /png ");p rivate void Postmultipartbody () {okhttpclient client = new Okhttpclient (); Use the Imgur image upload API as documented at https://api.imgur.com/endpoints/image multipartbody BODY = new Multi Partbody.builder ("aab03x"). SetType (Multipartbody.form). Addpart (Headers.of ("Con Tent-disposition "," form-data; Name=\ "Title\"), Requestbody.create (null, "Square Logo"). Addpart (Head Ers.of ("Content-disposition", "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). ur    L ("Https://api.imgur.com/3/image"). Post (body). Build (); Pager Call = Client.newcall (request); Call.enqueue (New Callback () {@Override public void onfailure (call call, IOException e) {} @O Verride public void Onresponse (call call, Response Response) throws IOException {System.out.println (res        Ponse.body (). String ()); }    });}
3. Interceptor-interceptor

Okhttp's interceptor chain is the essence of its entire framework, and users can pass interceptor into two categories:
The ① class is global interceptor , which is interceptor called first in the entire interceptor chain and passed in OkHttpClient.Builder#addInterceptor(Interceptor) ;
② Another class is non-Web request interceptor , this kind of interceptor will only be called in the non-Web request, and is after the assembly of the request, the actual network request is called before, all interceptor are saved in the List<Interceptor> interceptors collection, in accordance with the order of addition to call, the specific method can be referenced RealCall#getResponseWithInterceptorChain() . by OkHttpClient.Builder#addNetworkInterceptor(Interceptor) passing in;

Here's a simple example of a requirement that I want to monitor OkHttp all the original requests made by the app, as well as the time spent on the entire request, and use the first class of the global interceptor Interceptor chain header for this requirement.

  okhttpclient okhttpclient = new Okhttpclient.builder (). Addinterceptor (New Logginginterceptor ()) . build (); Request Request = new Request.builder (). URL ("Http://www.publicobject.com/helloworld.txt"). Header ("User-age NT "," OkHttp Example "). Build (); Okhttpclient.newcall (Request). Enqueue (New Callback () {@Override public void    OnFailure (call call, IOException e) {log.d (TAG, "onfailure:" + e.getmessage ()); } @Override public void Onresponse (call call, Response Response) throws IOException {Responsebody BODY = Res        Ponse.body ();            if (BODY = null) {LOG.D (TAG, "onresponse:" + response.body (). String ());        Body.close (); }    }});
public class LoggingInterceptor implements Interceptor {    private static final String TAG = "LoggingInterceptor";        @Override    public Response intercept(Chain chain) throws IOException {        Request request = chain.request();        long startTime = System.nanoTime();        Log.d(TAG, String.format("Sending request %s on %s%n%s",                request.url(), chain.connection(), request.headers()));        Response response =  chain.proceed(request);        long endTime = System.nanoTime();        Log.d(TAG, String.format("Received response for %s in %.1fms%n%s",                response.request().url(), (endTime - startTime) / 1e6d, response.headers()));        return response;    }}

For this request, print out the results

Sending request http://www.publicobject.com/helloworld.txt on nullUser-Agent: OkHttp Example        Received response for https://publicobject.com/helloworld.txt in 1265.9msServer: nginx/1.10.0 (Ubuntu)Date: Wed, 28 Mar 2018 08:19:48 GMTContent-Type: text/plainContent-Length: 1759Last-Modified: Tue, 27 May 2014 02:35:47 GMTConnection: keep-aliveETag: "5383fa03-6df"Accept-Ranges: bytes

Note that the point is that this request has been redirected, the original request url is http://www.publicobject.com/helloworld.tx , and the response request url is https://publicobject.com/helloworld.txt that this indicates that a redirect must have occurred, but we did a couple of redirects in fact we do not know here, to know these words, you can use addNetworkInterceptor() to do. For more information about interceptor use and their respective strengths and weaknesses, please visit the Okhttp official documentation.

4. Other
    1. It is recommended that OkHttpClient you keep the singleton, using the same OkHttpClient instance to execute all your requests, because each OkHttpClient instance has its own connection pool and thread pool, reusing these resources can reduce latency and conserve resources, and if an instance is created for each request OkHttpClient , it is obviously a waste of resources. Of course, you can also create a new instance by sharing the OkHttpClient connection pool, thread pool, and configuration information in the following ways.
    OkHttpClient eagerClient = client.newBuilder()        .readTimeout(500, TimeUnit.MILLISECONDS)        .build();    Response response = eagerClient.newCall(request).execute();
    1. Each call (in fact, now a realcall) can only be executed once, otherwise it will report an exception, specifically seeRealCall#execute()

Related reading

    • Basic use of 1.Okhttp
    • 2.Okhttp Mainstream Routines Code analysis
    • 3.OKHTTP3 architecture analysis, mainly through some flowchart class show

Use of Okhttp

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.