The following are the characteristics of OKHTTP given by the official website:
- Support HTTP/2. HTTP/2 supports concurrency on a separate TCP connection by using multiplexing technology, sending or receiving data by sending multiple requests at one time on a connection;
- If HTTP/2 is not available, connection pool multiplexing technology can also greatly reduce delays;
- Transparent Gzip processing reduces the size of communication data
- Response cache completely avoids duplicate requests in the network
- Use Okio to simplify data access and storage and improve performance
- If your server has multiple IP addresses configured, OkHttp will automatically try the next IP when the first IP connection fails.
- OkHttp also handles proxy server issues and SSL handshake failure issues;
Official website address:/okhttp/
Configuration
Add OKHttp dependency
implementation '.okhttp3:okhttp:3.12.3'
Add network permissions, if you need file read and write file read and write permissions
<uses-permission android:name="" /> <uses-permission android:name=".WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name=".READ_EXTERNAL_STORAGE" />
Next, you can happily start using OKhttp for development.
Create OkHttpClient
OKhttpclient is built through builder. There are many configuration items involved during construction. This time, some of them are briefly explained, and some important configuration items will be explained in the future. The configuration items in actual projects are configured according to the specific requirements of the project.
builder = new (); //Cache directory File externalCacheDir = (); if (externalCacheDir != null) { Cache okHttpCache = new Cache(new File(externalCacheDir, "HttpCache"), 30 * 1024 * 1024); (okHttpCache); } //Connection timeout time, connection timeout is applied when connecting TCP SOCKET to the target host, default 10s (30, ); //Read timeout, including TCP SOCKET, Source and Response read IO operations, default 10s (20, ); //Write timeout, mainly refers to IO write operation, default 10s (20, ); //The timeout time of the entire calling period includes parsing DNS, linking, writing request body, server processing, and reading response results (120, ); //It can be used for parsing time-consuming calculations for a single client to listen to all parsing events. (); //Add an interceptor. Some interceptors have been added by default within the framework. The interceptors added through the interface are at the beginning of the list. (new LogInterceptor()); //Add a network interceptor, the network interceptor can operate the return value of redirection and failed reconnection, as well as monitor all network data (new NetworkInterceptor()); // During the handshake, if the hostname of the URL and the server's identity hostname do not match, the verification mechanism can call back the implementer of this interface to determine whether this connection should be allowed. //Return false means that this link is not allowed, and the brainless return true is very unsafe (new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); //Authorization, default is// (); //Connection pool, default 5 idle connections, connection keeps alive for 5 minutes// (new ConnectionPool()); //Customize CookieJar, default CookieJar.NO_COOKIES// (CookieJar.NO_COOKIES); //Scheduling policy, the default maximum concurrency number is 64, but the default maximum number of requests for each domain name is 5// (new Dispatcher()); //Configure certificate authentication policy// (); OkHttpClient client = ();
The most commonly used configuration items are
- Cache file path and cache capacity size
- Timeout time for link, read, write requested by network
- Interceptor, this is the most commonly used in OKHTTP, and can be used to handle functions such as retry, caching, log printing, etc.
- Verification of domain names and certificates
- Connectors and concurrent scheduling strategies, etc.
Synchronize get requests
public void synGet(String url) { // The first step is to build HttpUrl builder = null; try { HttpUrl httpUrl = (url); if(httpUrl != null){ builder = (); } } catch (IllegalArgumentException e) { (); } if (builder == null) { return; } ("key","value"); // The second step is to build the Request request object Request request = new () //Request address .url(httpUrl) //Get request, default is get request .get() //Add a request header, a key corresponds to multiple values, which can be customized .addHeader("key", "value") .addHeader("key", "value1") //Request header, one-to-one, such as common Content-Type, Accept-Encoding, etc. .header("key1", "value1") //Cache policy, currently using forced network request .cacheControl(CacheControl.FORCE_NETWORK) //Cache Policy .build(); try { //Step 3, start synchronous request Response response = client .newCall(request) .execute(); //Step 4, parse the response result ResponseBody body = (); if (body != null) { (TAG, ()); } } catch (IOException e) { (); } }
Synchronous get requests will block the current thread until the result is returned. The request is roughly divided into four steps:
- Build HttpUrl, of course, this step is not necessary, you can also directly pass the address to it.
- The second step is to build the Request request object, which can set the request header, cache policy, and request method.
- Step 3: Start synchronous request
- Analyze the response result
Note: The synchronous get request must be performed in the child thread, and the application will throw exceptions.
Asynchronous get request
The steps of asynchronous request method are basically the same as the previous two steps above. The main method of initiating the request has changed, and the result is returned through a callback. This request method has no restrictions on the requested thread.
// The first step is to build HttpUrl// The second step is to build the Request request object//Step 3, start asynchronous request(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { //Step 4, parse the response result ResponseBody body = (); if (body != null) { (TAG, ()); } } });
Synchronize post requests
public void synPost(String url) { // The first step is to build HttpUrl builder = null; try { HttpUrl httpUrl = (url); if (httpUrl != null) { builder = (); } } catch (IllegalArgumentException e) { (); } if (builder == null) { return; } //Second step, build RequestBody MediaType mediaType = ("application/json;charset=UTF-8"); JSONObject jsonObject = new JSONObject(); try { ("key1", "value1"); ("key2", "value2"); } catch (JSONException e) { (); } RequestBody requestBody = (mediaType, ()); // The third step is to build the Request request object Request request = new () .url(()) .post(requestBody) .build(); //Step 4, start synchronous post request try { Response response = (request).execute(); //Step 5, parse the request result ResponseBody body = (); if (body != null) { (TAG, ()); } } catch (IOException e) { (); } }
Unlike the get request method, the post request requires the construction of the RequestBody, which carries the RequestBody when requesting.
Asynchronous post request
public void asynPost(String url) { // The first step is to build HttpUrl //Second step, build RequestBody // The third step is to build the Request request object Request request = new () .url(()) .post(requestBody) .build(); (request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { ResponseBody body = (); if (body != null) { (TAG, ()); } } }); }
Upload file
//The first step is to build HttpUrl //Second step, build RequestBody MediaType mediaType = ("multipart/form-data; charset=utf-8"); RequestBody requestBody = (mediaType, file); //The third step is to build a MultipartBody MultipartBody body = new () .setType() // Add multiple requestBody here to achieve multiple file upload .addFormDataPart("file", (), requestBody) .build(); // Step 4: Build the Request request object Request request = new () .url(()) .post(body) .build(); // Step 5: Build the Request Request object (request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { ResponseBody body = (); if (body != null) { (TAG, ()); } } });
Form Submission
//Second step, build RequestBody FormBody formBody = new () .add("key1","value1") .add("key2","value2") .build(); // The third step is to build the Request request object Request request = new () .url(()) .post(formBody) .build(); (request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { ResponseBody body = (); if (body != null) { (TAG, ()); } } });
The above is the detailed content of the introduction to the use of OKHttp. For more information about the use of OKHttp, please follow my other related articles!