删除 Android 中特定改造请求的标头

Mag*_*xus 4 android kotlin retrofit2

设置此类拦截器后有没有办法删除特定标头:

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)
Run Code Online (Sandbox Code Playgroud)

这是我的改造实例:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 API 服务:

interface ApiService {
    @GET("/app/shoes")
    fun getShoes() : Call<Shoes>
}
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助 :)

Key*_*öze 21

向 API 调用添加标头,指示是否添加身份验证标头。就像这样:

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>
}
Run Code Online (Sandbox Code Playgroud)

检查 中的标头Interceptor,如果满足条件则添加标头。就像这样:

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())
    }
}
Run Code Online (Sandbox Code Playgroud)