OkHttp is an HTTP client.
characteristic:
- Connection pooling reduces request latency (when HTTP/2 is not available)
- Reduce download volume when transmitting GZIP
- Cache replies to the same request
OkHttp can recover silently from connection failure. If the service has multiple IP addresses, it will try other addresses if the first access fails. This function is necessary for IPv4+IPv6 and multiple host services.
OkHttp supports modern TLS features.
requirement:
- Currently, OkHttp requires Android 5.0+ (API level 21 +) or Java 8 +.
- OkHttp relies on Okio and Kotlin standard libraries. Officials strongly recommend that we keep OkHttp updated.
- OkHttp 3.12.x supports Android 2.3+ (API level 9 +) and Java 7 +.
Next, we will introduce the use of OkHttp in Android development.
Android introduces dependency
First, OkHttp dependency is introduced
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
Take gitee open API as an example https://gitee.com/api/v5/swagger , take the interface here as an example. You need to prepare your gitee account.
The following is the actual operation of GET and POST, developed with Kotlin.
GET
The user of the star warehouse is listed
This is a GET interface.
url: https://gitee.com/api/v5/repos/rustfisher/AndroidTutorial/stargazers?page=1&per_page=20
You can get the result with curl command
curl -X GET --header 'Content-Type: application/json;charset=UTF-8' 'https://gitee.com/api/v5/repos/rustfisher/AndroidTutorial/stargazers?page=1&per_page=20'
Initiate GET request
private fun get1() { val client = OkHttpClient() val request = Request.Builder().url("https://gitee.com/api/v5/repos/rustfisher/AndroidTutorial/stargazers?page=1&per_page=20") .build() request.header("Content-Type: application/json;charset=UTF-8") client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.d(TAG, "[get1] onFailure: $call\n$e") } override fun onResponse(call: Call, response: Response) { Log.d(TAG, "[get1] onResponse: $call\n$response") if (response.code == 200) { // Request succeeded! Response. Body string() } } }) }
- Create OkHttpClient client object client
- Then create the request object request
- Request set header, request. Header ("content type: application / JSON; charset = UTF-8")
- Give the request to the client to join the request queue
- Enqueue (object: Callback) method can pass in a Callback
- The requested result is in response.body
POST
Create code snippets
gitee has the function of code snippets. Take the interface of creating code snippets as an example.
Interface documentation: https://gitee.com/api/v5/swagger#/postV5Gists
The following is the interface description
Parameter | Value | Description | Type | Data Type |
---|---|---|---|---|
access_token (required) | (login gitee to get) | User authorization code | formData | string |
files (required) | Code snippet file name and content. For example: | formData | object | |
description (required) | Code fragment description, 1 ~ 30 characters | formData | string | |
public | Public / private, default: private | formData | boolean |
Related code
private fun post1() { val mediaType = "application/json; charset=utf-8".toMediaType() val client = OkHttpClient() val postData = buildJson1() val body = buildJson1().toString().toRequestBody(mediaType) Log.d(TAG, "post1: $postData") val request = Request.Builder().url("https://gitee.com/api/v5/gists") .post(body) .build() val resp = client.newCall(request).execute() // Immediate execution blocks the current thread if (resp.code >= 200 || resp.code <= 201) { val resStr = resp.body!!.string() Log.d(TAG, "post1: resp body: $resStr") mHandler.post { binding.resTv.text = resStr } } } private fun buildJson1(): JSONObject { val map = HashMap<String, Any>() map["access_token"] = "0d6f65ef07976154138e126764303622" val file1Map = HashMap<String, Any>() file1Map["content"] = "# POST test \ n rustfisher.com“ val file2Map = HashMap<String, Any>() file2Map["content"] = "# Second file \ n an.rustfisher.com“ val filesMap = HashMap<String, Any>() filesMap["file1"] = file1Map filesMap["file2"] = file2Map map["files"] = filesMap map["description"] = "test POST Interface" return JSONObject(map as Map<*, *>) }
Here, you need to report some information and load the information with JSONObject. The obtained json content is converted to RequestBody.
Finally, it is handed over to the OkHttp client to execute the request. Note that you need to operate in the child thread.
Okhttp related source code analysis:
- Okhttp request process
- RealCall#enqueue(Callback)
- RealInterceptorChain#proceed()
[Android Development: Framework source code analysis video reference]