Okhttp 拦截器无法显示 401(未验证)响应

Okhttp interceptor not working showing 401(Unauthenticated) response

OKHTTP 拦截器不工作它给了我 401 响应(Unauthenticated/UnAuthorized)

这是我的拦截器Class

拦截器Class

class NetworkInterceptor(context: Context) : 拦截器 {

private val applicationContext = context.applicationContext
private val sharedPreferenceData = SharedPreferenceData(applicationContext)

override fun intercept(chain: Interceptor.Chain): Response {

    if (!isConnectionAvailable()) {
        throw NoConnectionException("Error! Connecting to the network")
    } else {
        val requestBuilder = chain.request().newBuilder()
        val token = sharedPreferenceData.getString("token", "")
        requestBuilder.addHeader("Authorization", "Bearer $token")
        Log.e("Token", "intercept: $token")
        return chain.proceed(requestBuilder.build())
    }
}

@Suppress("DEPRECATION")
fun isConnectionAvailable(): Boolean {
    val cm =
        applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    cm.activeNetworkInfo.also {
        return it != null && it.isConnected
    }
}

}

这里是网络实例class

object NetworkInstance {
    fun getApi(context: Context): DataApi {
        val gsonBuilder = GsonBuilder()
        gsonBuilder.setLenient()
        val gson = gsonBuilder.create()
        val logging = HttpLoggingInterceptor()
        logging.setLevel(HttpLoggingInterceptor.Level.BODY)

        val client = OkHttpClient
            .Builder()
            .addInterceptor(logging)
            .addInterceptor(NetworkInterceptor(context))
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .addInterceptor(logging)
            .build()

        val retrofit = Retrofit
            .Builder()
            .client(client)
            .baseUrl(BuildConfig.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
        return retrofit.create(DataApi::class.java)
    }

}

这个问题是因为我的愚蠢。我在 build.gradle 中添加了 BASE_URL,这会在 BuildCondig.java 中生成一个无法更改的 Static Final 变量。添加时 header BASE_URL 无法更改。