Brief introduction to the use of Android OKHttp
- 2021-12-12 10:00:14
- OfStack
The following are the characteristics of OKHTTP given by official website:
Support HTTP/2, HTTP/2 supports concurrency on a single TCP connection by using multiplexing technology, and sends or receives data by sending multiple requests at one time on a connection; If HTTP/2 is not available, the connection pool multiplexing technology can also greatly reduce the delay; Transparent Gzip processing reduces the size of communication data Response caching completely avoids repeated requests in the network Use Okio to simplify data access and storage and improve performance If your server is configured with multiple IP addresses, OkHttp will automatically try the next IP when the first IP connection failsOkHttp also addresses proxy server issues and SSL handshake failures;
Official website address: square.github.io/okhttp/
Configure
Add an OKHttp dependency
implementation 'com.squareup.okhttp3:okhttp:3.12.3'
Add network permissions, if you need to read and write files, read and write files
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Next, you can happily start developing with OKhttp.
Create OkHttpClient
OKhttpclient is built through builder, which involves many configuration items. This time, one of them is briefly explained, and one of the important configuration items will be specially explained later. The configuration items in the actual project are configured according to the specific requirements of the project.
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// Cache directory
File externalCacheDir = context.getExternalCacheDir();
if (externalCacheDir != null) {
Cache okHttpCache = new Cache(new File(externalCacheDir,
"HttpCache"), 30 * 1024 * 1024);
builder.cache(okHttpCache);
}
// Connection timeout , The connection timeout occurs when the TCP SOCKET Applied when connecting to the target host, the default 10s
builder.connectTimeout(30, TimeUnit.SECONDS);
// Read timeout , Include TCP SOCKET And Source And Response Read of IO Action, default 10s
builder.readTimeout(20, TimeUnit.SECONDS);
// Write timeout, mainly refers to IO Write operation of, default 10s
builder.writeTimeout(20, TimeUnit.SECONDS);
// Timeout for the entire invocation period, including parsing DNS Link, write to the request body, server processing, and read the response result
builder.callTimeout(120, TimeUnit.SECONDS);
// Used for a single client That listens for all parsing events and can be used to parse time-consuming calculations
builder.eventListener(EventListener.NONE);
// Add interceptors. Some interceptors have been added by default inside the framework. Interceptors added through interfaces are at the top of the list
builder.addInterceptor(new LogInterceptor());
// Add a network interceptor, which can manipulate the return value of redirection and failed reconnection, and monitor all network data
builder.addNetworkInterceptor(new NetworkInterceptor());
// During the handshake, if URL The host name of does not match the identity host name of the server, and the authentication mechanism can call back the implementer of this interface to determine whether this connection should be allowed.
// Return false Indicates that this link is not allowed, no brain return true 10 Divided insecurity
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
// Authorization , Default to Authenticator.NONE
// builder.authenticator(Authenticator.NONE);
// Connection pool , Default 5 Idle connections, keep connections alive 5 Minutes
// builder.connectionPool(new ConnectionPool());
// Customize CookieJar, Default CookieJar.NO_COOKIES
// builder.cookieJar(CookieJar.NO_COOKIES);
// Scheduling strategy , The default maximum concurrency number defaults to 64 But the maximum number of requests per domain name Default to 5 A
// builder.dispatcher(new Dispatcher());
// Configure Certificate Authentication Policy
// builder.sslSocketFactory();
OkHttpClient client = builder.build();
Among the above configuration items, the following are commonly used
Cache file path and cache capacity Timeout of link, read and write of network request Interceptor, which is the most commonly used in OKHTTP, can be used to handle functions including retry, caching, log printing and so on Verification of domain name and certificate Connector and concurrent scheduling strategy, etc.
Synchronize get requests
public void synGet(String url) {
// No. 1 1 Step, build HttpUrl
HttpUrl.Builder builder = null;
try {
HttpUrl httpUrl = HttpUrl.parse(url);
if(httpUrl != null){
builder = httpUrl.newBuilder();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
if (builder == null) {
return;
}
builder.addQueryParameter("key","value");
// No. 1 2 Step, build Request Request object
Request request = new Request.Builder()
// Request address
.url(httpUrl)
//get Request, default to get Request
.get()
// Add a request header, 1 A key Corresponding to multiple value Can be customized
.addHeader("key", "value")
.addHeader("key", "value1")
// Request header, 1 Right 1 Of, as is common Content-Type , Accept-Encoding Etc
.header("key1", "value1")
// Caching policy, currently using mandatory network requests
.cacheControl(CacheControl.FORCE_NETWORK)
// Caching policy
.build();
try {
// No. 1 3 Step , Start synchronization request
Response response = client
.newCall(request)
.execute();
// No. 1 4 Step, analyze the response result
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, body.string());
}
} catch (IOException e) {
e.printStackTrace();
}
}
Synchronizing an get request blocks the current thread until a result is returned, and the request is roughly divided into four steps:
Build HttpUrl. Of course, this step is not necessary, and you can also pass in the address directly Step 2: Construct the Request request object. You can set the request header, cache policy and request mode Step 3, start the synchronization request Analytical response resultNote: Synchronize get request should be made in child thread. If it is not applied, an exception will be thrown.
Asynchronous get request
The steps of asynchronous request mode are basically the same as the first two steps mentioned above. The main way of initiating the request has changed, and the result is returned through callback. This request mode has no restrictions on the requesting thread.
// No. 1 1 Step, build HttpUrl
// No. 1 2 Step, build Request Request object
// No. 1 3 Step , Start an asynchronous request
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// No. 1 4 Step, analyze the response result
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, body.string());
}
}
});
Synchronize post requests
public void synPost(String url) {
// No. 1 1 Step, build HttpUrl
HttpUrl.Builder builder = null;
try {
HttpUrl httpUrl = HttpUrl.parse(url);
if (httpUrl != null) {
builder = httpUrl.newBuilder();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
if (builder == null) {
return;
}
// No. 1 2 Step, build RequestBody
MediaType mediaType = MediaType.parse("application/json;charset=UTF-8");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("key1", "value1");
jsonObject.put("key2", "value2");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
// No. 1 3 Step, build Request Request object
Request request = new Request.Builder()
.url(builder.build())
.post(requestBody)
.build();
// No. 1 4 Step , Start synchronization post Request
try {
Response response = client.newCall(request).execute();
// No. 1 5 Step, parse the request result
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, body.string());
}
} catch (IOException e) {
e.printStackTrace();
}
}
Different from get request mode, post request needs to build RequestBody and carry RequestBody when requesting.
Asynchronous post request
public void asynPost(String url) {
// No. 1 1 Step, build HttpUrl
// No. 1 2 Step, build RequestBody
// No. 1 3 Step, build Request Request object
Request request = new Request.Builder()
.url(builder.build())
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, body.string());
}
}
});
}
Upload a file
// No. 1 1 Step, build HttpUrl
// No. 1 2 Step, build RequestBody
MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
RequestBody requestBody = RequestBody.create(mediaType, file);
// No. 1 3 Step, build MultipartBody
MultipartBody body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
// Add multiple requestBody Realize multi-file upload
.addFormDataPart("file", file.getName(), requestBody)
.build();
// No. 1 4 Step, build Request Request object
Request request = new Request.Builder()
.url(builder.build())
.post(body)
.build();
// No. 1 5 Step, build Request Request object
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, body.string());
}
}
});
Form submission
// No. 1 2 Step, build RequestBody
FormBody formBody = new FormBody.Builder()
.add("key1","value1")
.add("key2","value2")
.build();
// No. 1 3 Step, build Request Request object
Request request = new Request.Builder()
.url(builder.build())
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
if (body != null) {
Log.d(TAG, body.string());
}
}
});
The above is the OKHttp use of the introduction of the details, more information about the use of OKHttp please pay attention to other related articles on this site!