Skip to main content

How to add headers to a request using OKHTTP in Kotlin Android

How to add headers to a request using OKHTTP in Kotlin Android.

Here's a detailed step-by-step tutorial on how to add headers to a request using OKHTTP in Kotlin Android:

Step 1: Add the OKHTTP dependency to your project

Add the following dependency to your project's build.gradle file:

dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
}

Step 2: Create an instance of the OkHttpClient

In your Kotlin file, create an instance of the OkHttpClient class:

val client = OkHttpClient()

Step 3: Create a new request and add headers

To add headers to a request, create a new instance of the Request.Builder class, set the desired headers using the header() method, and build the request:

val request = Request.Builder()
.url("https://api.example.com/endpoint")
.header("Authorization", "Bearer <your_token>")
.header("Content-Type", "application/json")
.build()

In the example above, we added two headers: Authorization and Content-Type. You can add as many headers as needed.

Step 4: Make the network request

To make the network request, create an instance of the Call class using the newCall() method of the OkHttpClient and enqueue the call:

val call = client.newCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// Handle network request failure
}

override fun onResponse(call: Call, response: Response) {
// Handle network request success
}
})

In the onFailure() method, you can handle any network request failures, such as a lack of network connectivity. In the onResponse() method, you can handle the response from the server.

Step 5: Execute the network request synchronously

If you want to execute the network request synchronously (blocking the current thread), you can use the execute() method instead of enqueue():

val response = client.newCall(request).execute()

Keep in mind that executing the request synchronously on the main thread can cause your app to freeze, so it's generally recommended to use the asynchronous approach.

That's it! You have successfully added headers to a request using OKHTTP in Kotlin Android. Feel free to modify the code example to suit your specific use case.