Android Getting Started tutorial | OkHttp getting started

OkHttp is an HTTP client.


  • 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.


  • 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 , 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.


The user of the star warehouse is listed

This is a GET interface.

You can get the result with curl command

curl -X GET --header 'Content-Type: application/json;charset=UTF-8' ''

Initiate GET request

private fun get1() {
    val client = OkHttpClient()
    val request = Request.Builder().url("")
    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


Create code snippets

gitee has the function of code snippets. Take the interface of creating code snippets as an example.

Interface documentation:

The following is the interface description

ParameterValueDescriptionTypeData Type
access_token (required)(login gitee to get)User authorization codeformDatastring
files (required) Code snippet file name and content. For example:formDataobject
description (required) Code fragment description, 1 ~ 30 charactersformDatastring
public Public / private, default: privateformDataboolean

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("")
    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") { 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“
    val file2Map = HashMap<String, Any>()
    file2Map["content"] = "# Second file \ n“
    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]

Keywords: Android OkHttp

Added by roy on Mon, 22 Nov 2021 08:02:21 +0200