Okhttp 拦截器无法正常工作,显示 401(未经身份验证)响应

发布于 2025-01-10 15:54:20 字数 1992 浏览 0 评论 0原文

OKHTTP拦截器不工作它给了我401响应(未经身份验证/未经授权)

这是我的拦截器类

InterceptorClass

类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
    }
}

}

这是网络实例类

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)
    }

}

OKHTTP Interceptor not working It gives me 401 Response(Unauthenticated/UnAuthorized)

Here is my Interceptor Class

InterceptorClass

class NetworkInterceptor(context: Context) : Interceptor {

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
    }
}

}

Here is the network instance 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)
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

走走停停 2025-01-17 15:54:20

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

The issue was because of my Stupidity. I have added BASE_URL inside build.gradle which generates a Static Final variable inside BuildCondig.java which can't be altered. While Adding header BASE_URL can't be changed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文