【问题标题】:Http requests with OkHttp Interceptor doesn't works使用 OkHttp 拦截器的 Http 请求不起作用
【发布时间】:2021-08-13 11:16:09
【问题描述】:

我正在使用带有 OkHttp 拦截器的 Retrofit 来处理 API。 拦截器向每个请求添加 cookie 标头。 拦截器代码:

class AddCookiesInterceptor: Interceptor {

    @Inject
    lateinit var cookiesDao: CookiesDao

    init {
        App.getAppComponent().inject(this)
    }

    @SuppressLint("CheckResult")
    override fun intercept(chain: Interceptor.Chain): Response {
        val builder = chain.request().newBuilder()
        cookiesDao.getAll()
            .subscribeOn(Schedulers.io())
            .subscribe { cookies ->
            builder.addHeader("Cookie", "JWT=" + cookies.jwt)
        }
        return chain.proceed(builder.build())
    }
}

在调试时我看到,拦截器更新请求并添加带有值的 cookie 标头,但是当服务器到达请求时它返回错误(再次 400 http 代码身份验证)。 如果我像这样手动将标头添加到请求中

    @GET("/api.tree/get_element/")
    @Headers("Content-type: application/json", "X-requested-with: XMLHttpRequest", "Cookie: jwt_value")
    fun getElementId(): Maybe<ResponseBody>

Api 返回 200 个 http 代码,它可以工作。

【问题讨论】:

  • 如果省略"JWT=" +会怎样?
  • @Jameido 请求需要授权。没有令牌 (JWT) 服务器返回“400 - 错误请求”和消息“再次授权”
  • 我的意思是这样做builder.addHeader("Cookie", cookies.jwt)

标签: android kotlin okhttp


【解决方案1】:

您的代码无法正常工作,因为您正在异步添加标头,这是您的流程中发生的事情的“时间线”:

init builder -> 请求 cookie -> 继续链 -> 接收 cookies dao 回调 -> 将 header 添加到已经使用的 builder

您需要做的是同步检索 cookie,为此您可以使用 BlockingObseervable 并获得类似的东西。 使用同步函数不会造成任何问题,因为拦截器已经在后台线程上运行。

@SuppressLint("CheckResult")
override fun intercept(chain: Interceptor.Chain): Response {
    val builder = chain.request().newBuilder()
    val cookies = cookiesDao.getAll().toBlocking().first()
    builder.addHeader("Cookie", "JWT=" + cookies.jwt)
   
    return chain.proceed(builder.build())
}

【讨论】:

  • 谢谢你的回答。我认为 BlockingObservable 是在 RxJava 3 中添加的,我的 RxJava2 库中没有这些类和方法。我试过cookiesDao.getAll().blockingFirst() 但它不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 2014-05-26
  • 2018-02-02
  • 1970-01-01
相关资源
最近更新 更多