8.4 OkHttp

​OkHttp is a third-party library developed by Square for sending and receive HTTP-based network requests.

Using OkHttp

Setting up

Add the following dependencies in your module-level build.gradle file:
// Plugins should be located at the very top of your file
apply plugin: 'kotlin-kapt'
​
// Alternative if your plugins look like this!
plugins {
...
id 'kotlin-kapt'
}
​
...
​
dependencies {
// define a BOM and its version
implementation(platform("com.squareup.okhttp3:okhttp-bom:4.9.3"))
​
// define any required OkHttp artifacts without version
implementation("com.squareup.okhttp3:okhttp")
implementation("com.squareup.okhttp3:logging-interceptor")
}
In the case of OkHttp, we will need internet permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

GET

How can we execute GET requests using OkHttp? We can make an asynchronous GET call using the enqueue, which will tell us through the callback once the request has completed.
private val client = OkHttpClient()
​
fun run() {
val request = Request.Builder()
// URL given from API/Backend (make sure the URL + path
// is corect for the given get request
.url(...)
// can also add headers with .addHeader e.g .addHeader("Authorization", "Bearer ${TOKEN}")
.get()
.build()
​
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: java.io.IOException) {
e.printStackTrace()
}
​
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
// Can also respond with some UI saying check internet, try again, network request failed,
// etc. as opposed to exception (which will crash your app unless caught)!
throw IOException("Unexpected code $response")
} else {
// Can get access to the body with response.body(). Can then use
// Moshi techniques to convert said body to a Kotlin object if applicable
// or you can just parse the body directly!
val body = response.body
​
val blackjackHand = adapter.fromJson(body!!.source())
​
val jsonObject = JSONObject(body.string())
jsonObject.getString(KEY_NAME)
jsonObject.getInt(KEY_NAME)
...
}
}
})

POST

Post follows a very similar format to the GET request, except now we have to pass in some data into our request! There's lots of ways to do this depending on how the API wants the request to be formatted. Here we'll just showcase some examples that you can use to tailor to your needs:
private val client = OkHttpClient()
​
fun run() {
val blackjackHand = BlackjackHand(
Card('6', Suit.SPADES),
listOf(Card('4', Suit.CLUBS), Card('A', Suit.HEARTS))
)
// If our request body is meant to be an object representative of some
// class, we can leverage Moshi to help us build it.
val moshi: Moshi = Moshi.Builder().build()
val adapter: JsonAdapter<BlackjackHand> =
moshi.adapter<BlackjackHand>(BlackjackHand::class.java)
val json: String = adapter.toJson(blackjackHand)
val requestBody = json.toRequestBody("application/json".toMediaTypeOrNull())
​
// Alternative way of building a requestBody, directly
// setting the key/value pairs of the post body.
val jsonObject = JSONObject().apply {
put("card", json)
}
val requestBody = jsonObject.toString().toRequestBody("application/json".toMediaTypeOrNull())
val postRequest = Request.Builder()
.post(requestBody)
.url(...)
// Can also add headers with .addHeader e.g .addHeader("Authorization", "Bearer ${TOKEN}")
.build()
​
client.newCall(postRequest).enqueue(object : Callback {
override fun onFailure(call: Call, e: java.io.IOException) {
e.printStackTrace()
}
​
override fun onResponse(call: Call, response: Response) {
if (!response.isSuccessful) {
// Can also respond with some UI saying check internet, try again, network request failed,
// etc. as opposed to exception (which will crash your app unless caught)!
throw IOException("Unexpected code $response")
} else {
val body = response.body
​
// Some APIs as a response to a POST request may return objects right back,
// which we can then use Moshi to convert to a Kotlin object if
// we wish (like the imgur example above)
val blackjackHand = adapter.fromJson(body!!.source())
// Other times, APIs will return a sucess/failure boolean as a response,
// so parsing directly may a better alternative!
val jsonObject = JSONObject(body.string())
jsonObject.getString(KEY_NAME)
jsonObject.getInt(KEY_NAME)
...
}
}
})
}

Updating UI

The callbacks for OkHttp (methods like onFailure and onResponse) run on a background thread. If you want to immediately process something in the UI you will need to do your updates on the UI thread (which is the main, single thread that all Android applications run on).
The recommended way to do this is using the Android Jetpack architectural components of ViewModel and LiveData. The advantage of using these components is that they persist through Activity lifecycle changes so for example when the device orientation changes and the Activity is recreated, ViewModel and LiveData will persist and the information is reused in the created activity. Both of these components arise in discussions about app architecture in Android, which is outside the scope of this class.
See Android's guide to app architecture if you are interested in learning more!
For now, you can utilize the method runOnUiThread, which is usually executed within a worker thread to update UI:
client.newCall(postRequest).enqueue(object : Callback {
override fun onFailure(call: Call, e: java.io.IOException) {
e.printStackTrace()
}
​
override fun onResponse(call: Call, response: Response) {
runOnUiThread {
// Any UI updates here, e.g. creating Adapters, updating text, etc.
textView.text = response.body!!.string()
}
}
})
​