Detailed explanation of two request modes of OkHttp in Android small knowledge

  • 2021-10-16 04:55:08
  • OfStack

Preface

OkHttp is a very popular network library at present, which supports HTTP/2, allows all requests with the same host address to share the same socket connection, reduces request delay by connection pool, reduces the size of response data by transparent GZIP compression, caches response content, and avoids one completely duplicate request.

Before we start, we should first understand the following core classes:

OkHttpClient: Client Object Request: Access request, RequestBody needs to be included in Post request RequestBody: Request data, used in Post requests Response: That is, the response result of the network request MediaType: Data type, used to indicate that the data is in json, image, pdf and other series 1 formats client. newCall (request). execute (): Synchronous request method client. newCall (request). enqueue (Callback callBack): Asynchronous request method, but Callback is executed in a child thread, so UI update operation cannot be performed here

The following words are not much to say, let's take a look at the detailed introduction

OkHttpClient


private OkHttpClient mHttpClient = null;

 private void initHttpClient() {
  if (null == mHttpClient) {
   mHttpClient = new OkHttpClient.Builder()
     .readTimeout(5, TimeUnit.SECONDS)// Set read timeout 
     .writeTimeout(5,TimeUnit.SECONDS)//// Set write timeout 
     .connectTimeout(15,TimeUnit.SECONDS)// Set connection timeout 
     .retryOnConnectionFailure(true)// Whether to reconnect automatically 
     .build();
  }
 }

When you request a network using OkHttp, You need to get the client object OkHttpClient of OkHttp first, OkHttpClient can be created directly from new, It can also be created by OkHttpClient static inner class Builder, Daily development is most commonly created by build (builder mode + chain call). Static internal Builder provides many methods, such as readTimeout for read time, writeTimeout for write time, connectTimeout for connection timeout and retryOnConnectionFailure for reconnection, etc. With OkHttpClient, synchronous and asynchronous requests of the network can be made.

Synchronization request


private void synRequest() {
  Request request=new Request.Builder()
    .url("http://www.baidu.com")
    .get()
    .build();
  Call call=mHttpClient.newCall(request);
  try {
   Response response=call.execute();
   System.out.println(request.body().toString());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

When making a network request, it is necessary to create a request object Request first, and the Request object is also created by build. The static internal class Builder of Request defines the methods of setting the request address, request mode and request header.

Then create Call object, Call object can be understood as a bridge between Request and Response, and finally read Response through execute method of Call object.

The three steps to summarize the synchronization request are as follows:

Create OkHttpClient and Request objects. Encapsulates an Request object as an Call object. Call the execute () method of Call to send a synchronization request.

Note: Synchronization requests from OkHttp will block the current thread, so requests cannot be made in UI threads. You need to open sub-threads and send requests in sub-threads.

Asynchronous request


private void asyRequest() {
  final Request request=new Request.Builder()
    .url("http://www.baidu.com")
    .get()
    .build();
  Call call=mHttpClient.newCall(request);
  call.enqueue(new Callback() {
   @Override
   public void onFailure(Call call, IOException e) {

   }

   @Override
   public void onResponse(Call call, Response response) throws IOException {
    System.out.println(request.body().toString());
   }
  });
 }

The first two steps of asynchronous request and synchronous request are to create OkHttpClient and Request objects and encapsulate Request objects into Call objects, execute asynchronous request through enqueue method of Call object, enqueue passes in an Callback object, and Callback provides two callback methods, which are success and failure respectively.

The three steps to summarize asynchronous requests are as follows:

Create OkHttpClient and Request objects. Encapsulates an Request object as an Call object. Call the enqueue method of Call to make an asynchronous request.

Note: For the asynchronous request of OkHttp, the two callback methods onResponse and onFailure are executed in the worker thread, and the execution results can be sent through Handler.

Summarize


Related articles: