kotlin 在okhttpClient中将addheader初始化为全局

f0brbegy  于 2023-02-05  发布在  Kotlin
关注(0)|答案(1)|浏览(188)

由于我需要将add header初始化为全局,以便在所有API调用中获取头,我尝试过,但在调试时,它不会在API调用中发送头。

val client = OkHttpClient.Builder()
                .authenticator { _, response ->
                    response.request().newBuilder().addHeader(
                        "authorization","123").build()
                }
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build()
        AndroidNetworking.initialize(applicationContext, client)
2lpgd968

2lpgd9681#

你能用下面提到的代码替换你的代码并重试吗

OkHttpClient.Builder().add(new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                Request.Builder requestBuilder = chain.request().newBuilder();
                requestBuilder.header("Content-Type", "application/json");
                return chain.proceed(requestBuilder.build());
            }
        })
    .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build()
    AndroidNetworking.initialize(applicationContext, client)

相关问题