Search code examples
androidkotlinretrofit2

Remove header for a specific retrofit request in Android


Is there a way to remove a specific header after setting this kind of Interceptor :

public class AuthInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val original: Request = chain.request()
        val request: Request = original.newBuilder()
            .addHeader(AppConstant.HEADER_APP_TOKEN, AppConfig.apptoken) //<-- need to remove this one for only one request
            .addHeader(AppConstant.HEADER_SECURITY_TOKEN, AppConfig.security_token)
            .method(original.method(), original.body())
            .build()
        return chain.proceed(request)

Here is my Retrofit instance :

object RetrofitClientInstance {

    private val httpClient = OkHttpClient.Builder()
        .addInterceptor(AuthInterceptor())
        .addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))

    private val retrofit = Retrofit.Builder()
        .baseUrl(AppConstant.SERVER_BETA)
        .addConverterFactory(GsonConverterFactory.create())
        .client(httpClient.build())
        .build()

    fun <T> getRetrofitInstance(service: Class<T>): T {
        return retrofit.create(service)
    }
}

And this is my API Service :

interface ApiService {
    @GET("/app/shoes")
    fun getShoes() : Call<Shoes>
}

Thanks for your help :)


Solution

  • Add a header to API calls indicating whether to add auth headers or not. Like so:

    interface ApiService {
        @GET("/app/socks")
        fun getSocks() : Call<Socks>
    
    
        @Headers("isAuthorizable: true")
        @GET("/app/shoes")
        fun getShoes() : Call<Shoes>
    
        @Headers("isAuthorizable: true")
        @GET("/app/sandals")
        fun getSandals() : Call<Sandals>
    }
    

    Check the header in the Interceptor and add header if condition is satisfied. Like so:

    public class AuthInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val original: Request = chain.request()
    
            val shouldAddAuthHeaders = original.headers["isAuthorizable"] == "true"
            
            val requestBuilder = request
                .newBuilder()
                .method(request.method, request.body)
                .removeHeader("isAuthorizable")
            
            if (shouldAddAuthHeaders) {
                requestBuilder.addHeader(AppConstant.HEADER_APP_TOKEN, AppConfig.apptoken)
                        .addHeader(AppConstant.HEADER_SECURITY_TOKEN, AppConfig.security_token)
            }
    
            return chain.proceed(requestBuilder.build())
        }
    }