“This is the 11th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

OkHttp: An HTTP+HTTP/2 client for Android and Java Applications.

1. Basic knowledge

1.1 Introduction

OkHttp is a popular Http connection tool tripartite library, can be said to be built for high efficiency, is relatively simple to use.

OkHttp3 is widely used today, and this version is a big improvement over the previous OkHttp version. The implementation of this article is based on OkHttp3.

The website address

1.2 Importing Dependencies

Using OkHttp requires importing relevant Maven dependency information:

<! --OkHttp3-->
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>
Copy the code

2. Common class objects

2.1 OkHttpClient object

In OkHttp3, you need to create an OkHttpClient object. You can use the constructor directly to create the object. Or use the Builder pattern provided with OkHttp3 to create and return an object.

// use the constructor to initialize
OkHttpClient okHttpClient = new OkHttpClient();
​
// create and return objects using builder mode
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
Copy the code

The two object creation methods are essentially the same,

  1. When created using constructors, a constructor object is created by default and passed in as a parameter to create the OkHttpClient object;
  2. When creating with the Builder pattern, we also first create a builder object and call the build() method to pass in itself to return the OkHttpClient object.
// use the constructor
public OkHttpClient(a) { this(new OkHttpClient.Builder());    }
​
// use the builder mode
public OkHttpClient build(a) { return new OkHttpClient(this); }
Copy the code

2.2 the Request object

The Request object is a Request object for HTTP requests. OkHttp3 also uses the idea of the Builder pattern to create a Request object. When creating a Request object, it operates on the Inner Builder class of the Request class and passes properties to the Request object through the inner Builder class. The default request type when created is a GET request.

// Builder mode creates request objects, which default to GET requests
Request request = new Request.Builder().build();
Copy the code

If you want to customize the Request type, the Request class provides a method() method to specify the Request type, and further encapsulates the common Request methods, such as calling the.post() method to send the Request as post.

//method Specifies the request mode
public Request.Builder method(String method, @Nullable RequestBody body){... }// Encapsulates the get and POST methods, which can be called using the corresponding request type
public Request.Builder get(a) {
    return this.method("GET", (RequestBody)null);
}
public Request.Builder post(RequestBody body) {
    return this.method("POST", body);
}
Copy the code

The Request path can be specified using the URL () method of the Request object, which can pass in either a string or a URL object.

// Assign the builder object's URL attribute via the URL method. All other methods call this method indirectly
public Request.Builder url(HttpUrl url) {
    if (url == null) {
        throw new NullPointerException("url == null");
    } else {
        this.url = url;
        return this; }}Copy the code

In addition to methods for setting the Request type and path, the Request class also provides methods for setting the Request header information

// Set the request header
public Request.Builder header(String name, String value) {
    this.headers.set(name, value);
    return this;
}
// Append the request header information
public Request.Builder addHeader(String name, String value) {
    this.headers.add(name, value);
    return this;
}
// Set the request header information with the header object
public Request.Builder headers(Headers headers) {
    this.headers = headers.newBuilder();
    return this;
}
Copy the code

2.3 the Response object

A Response object is a Response object after an HTTP request. The Response class in OkHttp3 also uses the builder pattern.

In the Response object of HTTP, the common operation is to obtain the Response data from the Response result. The body() method is provided in the Response object to obtain the Response body content in the Response result.

// Get the corresponding body
@Nullable
public ResponseBody body(a) {
    return this.body;
}
Copy the code

3. Request process

3.1 GET request

The process for a GET request using the OkHttp tool is as follows

  1. Create the OkHttpClient object
  2. Create a Request object and set the Request type, Request path, and parameters
  3. The Request Request object is executed using the OkHttpClient object and the return result is received using the Response object
  4. Get the parse return data from the return result

The code implementation process can be expressed as:

//① Create the OkHttpClient object
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
// create a Request object
Request request = new Request.Builder().get().url(url).build();
//③ Execute the request and obtain the returned result
Response response = okHttpClient.newCall(request).execute();
//④ Obtain the returned data
response.body().toString();
Copy the code

3.2 a POST request

In contrast to GET, POST requests most of the time submit certain data information, and the process can be expressed as

  1. Create the OkHttpClient object
  2. Create request body object information
  3. Create a Request object, set the Request type to POST, and carry information about the Request body, Request path, and header parameters to be submitted
  4. The Request Request object is executed using the OkHttpClient object and the return result is received using the Response object
  5. Get the parse return data from the return result

The specific implementation code is as follows:

//① Create the OkHttpClient object
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
// create the request body information
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json)
//③ Create a Request object of type POST and pass in the Request body
Request request = new Request.Builder().post(requestBody).url(url).build();
//④ Execute the request and obtain the returned result
Response response = okHttpClient.newCall(request).execute();
//⑤ Get the returned data
response.body().toString();
Copy the code