OKHttp source code analysis 1: the use of synchronous and asynchronous requests

OKHttp synchronous request

It is mainly divided into four steps:
1. First, you need to create the OkHttpClient class, which is a client class. This class is a very important class in the entire OKHttp library. Many functions need to be forwarded and implemented through this client class. There are two creation methods, one is to create directly with new, and the other is to create through Builder, which can be used to set various parameters.

//创建OkHttpClient,这里只简单设置了超时时间为10
OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(10,TimeUnit.SECONDS).build();

2. Create a Request to request message body information. Generally, it is also created by Builder.

//创建Request
Request request = new Request.Builder().url("http://www.baidu.com").build();

3. Create a Call object, which represents the actual http request, a bridge connecting Request and Response. The Call object is actually an interface, and the real implementation is in the RealCall object.

//创建Call对象,代表实际的http请求,可以当做是连接Request和Response之间的桥梁
Call call = okHttpClient.newCall(request);

4. Call the execute() method of Call to complete the reading of the response message.

//同步调用execute()方法
Response response = call.execute();

The above four steps are the calling steps of the entire OKHttp synchronous request, and the following is the overall core code.

    //创建OkHttpClient,这里只简单设置了超时时间为10秒
    OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(10, TimeUnit.SECONDS).build();

    /**
     * 同步请求
     */
    private void syncRequest() {
        //创建Request
        Request request = new Request.Builder().url("http://www.baidu.com").build();
        //创建Call对象,代表实际的http请求,可以当做是Response与Request之间的桥梁
        Call call = okHttpClient.newCall(request);
        try {
            //同步调用execute()方法
            Response response = call.execute();
            Log.e("-----response----", response.body().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

It should be noted that after OKHttp sends a request synchronously, it will enter a blocking state until a response is received.


OKHttp asynchronous request

The first three steps of an asynchronous request are the same as those of a synchronous request, which are to create OKHttpClient and Request objects and to call newCall() to create a Call object through OKHttpClient. The fourth step is different. The enqueue() method of the Call object is called to make an asynchronous request. The code is as follows:

//创建OkHttpClient,这里只简单设置了超时时间为10秒
OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(10, TimeUnit.SECONDS).build();

/**
 * 异步请求
 */
private void asyncRequest() {
    //创建Request
    Request request = new Request.Builder().url("http://www.baidu.com").get().build();
    //创建Call对象,代表实际的http请求,可以当做是Response与Request之间的桥梁
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            Log.e("-----onFailure----", e.getMessage());
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Log.e("-----response----", response.body().toString());
        }
    });
}

It should be noted that both onFailure and OnResponse are executed in the worker thread, that is, in the child thread.

Summarize

  1. The method of initiating the request is different. The method called synchronously is execute(), and the asynchronous method is enqueue();
  2. Synchronization will block the current thread, while asynchronous will not, and a new child thread will be opened to handle network requests.

At this point, the basic use of OKHttp synchronous and asynchronous requests is finished. It is very simple and has very little content. But this is the starting point for us to analyze the OKHttp source code, so this chapter is still indispensable. In the next article, we will start to go deep into the OKHttp source code slowly, and appreciate the charm of the OKHttp source code step by step.

Next articleOKHttp source code analysis 2: synchronous request and asynchronous request process and source code analysis

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325193245&siteId=291194637