Skip to main content

How to add headers to requests using Retrofit in Kotlin Android

How to add headers to requests using Retrofit in Kotlin Android.

Here's a step-by-step tutorial on how to add headers to requests using Retrofit in Kotlin Android:

  1. Add Retrofit to your project:

    • Open your project's build.gradle file.
    • Add the Retrofit dependencies inside the dependencies block:
      dependencies {
      implementation 'com.squareup.retrofit2:retrofit:2.x.x'
      implementation 'com.squareup.retrofit2:converter-gson:2.x.x'
      }
    • Replace 2.x.x with the latest version of Retrofit.
  2. Create a data class to represent the headers:

    • Create a new Kotlin file, for example Headers.kt.
    • Inside the file, define a data class that represents the headers you want to include in your requests. For example:
      data class CustomHeaders(
      @SerializedName("Authorization") val authorization: String,
      @SerializedName("Content-Type") val contentType: String
      )
  3. Create an interface for your API:

    • Create a new Kotlin file, for example ApiService.kt.
    • Inside the file, define an interface that represents your API endpoints. For example:
      interface ApiService {
      @GET("endpoint")
      fun getData(): Call<YourResponseModel>
      }
  4. Create a Retrofit instance:

    • In your desired class, create a property for the Retrofit instance:
      private val retrofit = Retrofit.Builder()
      .baseUrl("https://api.example.com/")
      .addConverterFactory(GsonConverterFactory.create())
      .build()
  5. Create an interceptor to add headers to requests:

    • Create a new Kotlin file, for example HeaderInterceptor.kt.

    • Inside the file, define an interceptor class that implements Interceptor. This class will be responsible for adding the headers to the requests. For example:

      class HeaderInterceptor : Interceptor {
      override fun intercept(chain: Interceptor.Chain): Response {
      val originalRequest = chain.request()
      val modifiedRequest = originalRequest.newBuilder()
      .headers(createHeaders())
      .build()
      return chain.proceed(modifiedRequest)
      }

      private fun createHeaders(): Headers {
      val customHeaders = CustomHeaders(
      authorization = "your_authorization_token",
      contentType = "application/json"
      )
      return Headers.Builder()
      .add("Authorization", customHeaders.authorization)
      .add("Content-Type", customHeaders.contentType)
      .build()
      }
      }
  6. Add the interceptor to the Retrofit instance:

    • In the same class where you created the Retrofit instance, add the interceptor to it:

      private val retrofit = Retrofit.Builder()
      .baseUrl("https://api.example.com/")
      .addConverterFactory(GsonConverterFactory.create())
      .client(createOkHttpClient())
      .build()

      private fun createOkHttpClient(): OkHttpClient {
      return OkHttpClient.Builder()
      .addInterceptor(HeaderInterceptor())
      .build()
      }
  7. Create an instance of your API service:

    • In the same class, create a property for the API service instance:
      private val apiService = retrofit.create(ApiService::class.java)
  8. Make API requests with added headers:

    • Use the created API service instance to make requests with the added headers. For example:

      apiService.getData().enqueue(object : Callback<YourResponseModel> {
      override fun onResponse(
      call: Call<YourResponseModel>,
      response: Response<YourResponseModel>
      ) {
      if (response.isSuccessful) {
      val data = response.body()
      // Handle successful response
      } else {
      // Handle error response
      }
      }

      override fun onFailure(call: Call<YourResponseModel>, t: Throwable) {
      // Handle network failure
      }
      })

That's it! You have successfully added headers to requests using Retrofit in Kotlin Android.