Networking with Retrofit

6.1 Retrofit basics

Retrofit ( is a library written by Square, which makes working with HTTP(S) APIs a breeze.

You define an interface in Kotlin, which specifies the REST connection to the server.  REST is a way to communicate with servers in an idiomatic way. You can then use this interface and a class you create of the HTTP response, to get back a Kotlin object, which you can then use in your code.

One example of REST is performing a GET request for a list of items.  Another would be performing a DELETE on an item object.

6.2 Retrofit set up

In your build.gradle, in the app folder, in the dependencies section, place the following:

implementation ‘com.squareup.retrofit2:retrofit:(insert latest version)

You can find the latest version by visiting this page:

In a Kotlin file put the following code in a file called MyService:

interface MyService {


  fun listItems(@Path(“user”) String user): Call<List<Item>>


You can set up and retrieve data in the following way:

val retrofit= new Retrofit.Builder()



val service = retrofit.create(MyService.class);

val items = service.listItems(“john”);

Although this is quick and easy, it isn’t the only option for data transfer in Kotlin. You could also use only OKHttp ( to interact with REST services and get back a response string and then parse the JSON manually, or Picasso ( ) to load images into ImageViews easily. Picasso and OKHttp can be used in conjunction with Retrofit.

6.2 Retrofit Interceptors

In case you want to see what connections are being made behind the scenes, you can add an interceptor to Retrofit.  You can also use interceptors to add global headers to your request.

Register an interceptor by calling addInterceptor() on OkHttpClient.Builder:

val client = OkHttpClient.Builder()



After configuring your OKHttp client, you can tell Retrofit to use that client:

val retrofit = Retrofit.Builder()




In a new Kotlin file called LoggingInterceptor.kt place the following code. 

class LoggingInterceptor : Interceptor {


   val TAG = “LoggingInterceptor”



   override fun intercept(chain: Interceptor.Chain): Response {

       val request = chain.request()

       val t1 = System.nanoTime()



               “Sending request %s on %s%n%s”,

               request.url(), chain.connection(), request.headers()



       val response = chain.proceed(request)

       val t2 = System.nanoTime()



               “Received response for %s in %.1fms%n%s”,

               response.request().url(), (t2 – t1) / 1e6, response.headers()



       return response



Now your responses will include the URL and time it took to receive the response.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top