Okhttp profile

HTTP is a common network way for modern applications to exchange data and media. Efficient use of HTTP can make resources load faster and save bandwidth.

OKHttp is an efficient HTTP client that has the following default characteristics:

1. Supports Http/2, allowing all requests from the same host address to share the same socket connection
2. Connection pool reduces request latency
Transparent GZIP compression reduces the size of the response data
4. Cache response content to avoid some completely duplicate requests

HTTP/ 2 is the latest version of the Hypertext Transfer Protocol (HTTP), a new protocol. It is used to transmit data, which will greatly speed up the network and can help optimize search engines.

The Socket Interface is an Application Programming Interface (API) of the TCP/IP network. The Socket Interface defines many functions or routines that programmers can use to develop applications on the TCP/IP network.

OkHttp insists when the network goes wrong: it quietly recovers from common connection problems. If your service has multiple IP addresses, OkHttp will try an alternate address if the first connection fails. This is required for IPv4+IPv6 and services hosted in redundant data centers. OkHttp supports modern TLS functionality (TLS 1.3, ALPN, certificate locking). It can be configured to fall back for a wide range of connections.

Use:

Add permissions

<uses-permission android:name="android.permission.INTERNET"/>

Add the dependent

Implementation 'com. Squareup. Okhttp3: okhttp: 3.12.1'

OKHttp synchronous and asynchronous

1.1 synchronizing a synchronous request means that the program is blocked until the response result is received. The program cannot receive new requests until the response is received

The benefits of synchronous requests are: simple to understand; Simple implementation; The response results can be returned for subsequent processing;

The disadvantage of synchronous request is that it cannot support high concurrency, and the performance will be affected when the request response is not required to be real-time

1.2 asynchronous Asynchronous request refers to the non-blocking state after the request is initiated and until the response result is received, the program can continue to receive new requests. When the response comes back, a callback will be invoked to process the response data

The advantage of asynchronous requests is that they support highly concurrent interface requests

The disadvantages of asynchronous requests are: complex implementation; The response result can only be output but cannot be returned, which is unfavorable for subsequent processing of the interface

Asynchronous GET request -new OkHttpClient; -Construct Request object; – Build the Call object from the objects in the previous two steps; -submit asynchronous requests via Call#enqueue(Callback);

OkHttpClient okHttpClient = new OkHttpClient(); Final Request Request = new request.builder ().url(url).get() 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()); }});Copy the code

Asynchronously initiated requests are added to the Dispatcher’s runningAsyncCalls dual-end queue and executed through the thread pool.

The first few steps of a synchronous GET request are the same as those of an asynchronous one, but the last step is to submit the request through Call#execute(). Note that this method will block the calling thread, so it should be executed in the child thread on Android, otherwise it may cause ANR exception. Android3.0 does not allow access to the network from 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();
Copy the code