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

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.

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:

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:

Last updated

Was this helpful?