提问者:小点点

OkHttpClient不会向请求添加标头


我正在创建一个android应用程序,我正在使用改造来使用api网络服务。我的问题是当我使用注释添加标头时,它可以工作。

@Headers("Authorization: jwt-token")
@POST("appusers-service/signin/identification")
suspend fun authentication(@Body body : LoginIdentificationDto.Params) : NetworkResponse<LoginIdentificationDto.Result, LoginIdentificationDto.Errors>

但是当我使用拦截器动态添加标头时,它不起作用

@Provides
@Singleton
fun provideHttpClient() : OkHttpClient
{
    return OkHttpClient.Builder()
        .callTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .addNetworkInterceptor {
            
            val builder : Request.Builder = it.request().newBuilder()
            
            builder.addHeader(AUTHORIZATION_HEADER, "jwt-token")
            
            return@addNetworkInterceptor it.proceed(builder.build())
        }
        .build()
}

@Provides
@Singleton
fun provideRetrofit(httpClient : OkHttpClient, mapper : ObjectMapper) : Retrofit
{
    return Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(httpClient)
        .addCallAdapterFactory(NetworkResponseAdapterFactory())
        .addConverterFactory(JacksonConverterFactory.create(mapper))
        .build()
}

请问我如何解决这个问题?


共2个答案

匿名用户

试试这个吧

return OkHttpClient.Builder()
        .callTimeout(60, TimeUnit.SECONDS)
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .addInterceptor {
            val builder : Request.Builder = it.request().newBuilder()
            builder.addHeader(AUTHORIZATION_HEADER, "jwt-token")
            return@addNetworkInterceptor it.proceed(builder.build())
        }
        .build() 

请注意,我已将addNetworkInterceptor更改为addInterceptor。有关更多信息,您可以参考此答案https://stackoverflow.com/a/37120830/9394700

匿名用户

我正在做的方法是有一个类AuthInterceptor

class AuthInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val authenticatedRequest = request.newBuilder()
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", UserData.getAuthToken())
            .build()
        return chain.proceed(authenticatedRequest)
    }
}

并且在您的OkHtttpClient上这样使用。

val ohHttpClient = OkHttpClient.Builder()
ohHttpClient.addInterceptor(AuthInterceptor())