Detailed explanation of okhttp3 use in Android

1、 Import package

Add okhttp3 dependency in build.gradle under project module

2、 Basic use

1. Okhttp3 get method

1.1 okhttp3 synchronous get method

Request is the request object of okhttp3, and response is the response in okhttp3. Judge whether the request is successful through response. Issuccessful().

Get the returned data through response. Body(). String(). The default format is UTF-8; String () is suitable for obtaining small data information. If the returned data exceeds 1m, it is recommended to use stream () to obtain the returned data, because the string () method will load the whole document into memory.

Of course, you can also obtain the stream output form;

1.2 okhttp3 asynchronous get method

Sometimes it is necessary to download a file (such as a network image). If the file is large, the whole download will be time-consuming. Usually, we will put the time-consuming tasks into the working thread. Using okhttp3 asynchronous method, we do not need to start the working thread to execute the network request, and the returned results are also in the working thread;

Note: after Android 4.0, it is required that the network request must run in the worker thread and is no longer allowed to run in the main thread. Therefore, if you use okhttp3's synchronous get method, you need to start a new worker thread call.

1.3. Add request header

Okhttp3 to add a request header, you need to use. Header (string key, string value) or. AddHeader (string key, string value) in request. Builder(); Use. Header (string key, string value). If the key already exists, the value corresponding to the key will be removed, and then the new value will be added, that is, the original value will be replaced;

Using. AddHeader (string key, string value), even if the current value can already exist, only the new value will be added, and the original value will not be removed / replaced.

2. Okhttp3 post method

2.1. Post submits key value pairs

Many times, we need to send the key value pair data to the server through post, okhttp3 using formbody. Builder to create the requested parameter key value pair;

2.2 、Post a String

You can use the post method to send a string of strings, but it is not recommended to send text information of more than 1m. As shown in the following example, send a markdown text

2.3 、Post Streaming

Post can take the stream object as the request body and write the data in the form of output stream relying on okio;

2.4 、Post file

3. Other configurations

3.1. Gson resolves the gson object of the response

If the content of the response object is a JSON string, you can use gson to format the string as an object. ResponseBody. Charstream() uses the content type in the response header as the encoding method of the data returned by the response. The default is UTF-8.

3.2 okhttp3 local cache

The okhttp framework must have only one okhttpclient instance (New okhttpclient()) globally, and configure the cache path and size when creating the instance for the first time. As long as the cache is set, okhttp will automatically use the cache function by default.

Okhttpclient is a bit like the concept of application. It coordinates the functions of okhttp. Through setting the cache directory, we execute the above code and get the following results

The result of RESPONSE1 is in the networkresponse, which means that it is loaded from the network request, while the networkresponse of response2 is null, and the cachesphere has data. Because I set the cache, I find that there is in the cache the second time, so I don't go to the network request.

But sometimes even when there is a cache, we still need to go to the background to request the latest resources (such as resource updates). At this time, we can use forced network access to require that we must request network data

In the code above

The request corresponding to response2 becomes

Let's see the results

The cache response of response2 is null, and the network response still has data.

Similarly, we can use force_ Cache enforces the use of cached data only, but if the request has to obtain data from the network, but force is used_ The cache policy will return an error of 504. The code is as follows. We go to the cache of okhttpclient and set the request to force_ CACHE

3.3 okhttp3 cancel request

If a okhttp3 network request is no longer needed, call. Cancel() can be used to terminate the synchronous / asynchronous request being prepared. If a thread is writing a request or reading the returned response, it will receive an IOException.

3.4 okhttp3 timeout setting

Okhttp3 supports setting connection timeout and read-write timeout.

3.5 configuration of okhttp3 multiplexing okhttpclient

The proxy settings, timeout and cache settings of all HTTP requests need to be set in okhttpclient. If you need to change the configuration of a request, you can use okhttpclient. Newbuilder() to obtain a builder object that shares the same connection pool, configuration, etc. with the original okhttpclient.

In the following example, copy the configurations of two 'okhttpclients, and then set different timeout times respectively;

3.6 okhttp3 processing verification

Okhttp3 automatically retries unauthenticated requests. When a request returns 401 not authorized, an identifier needs to be provided.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>