【发布时间】:2017-08-30 23:32:34
【问题描述】:
将 Dropwizard+Jersey 用于用户使用其用户名/密码登录的 Web 应用程序,并创建带有用户 ID 的 cookie。他们在每个请求中发回这个用户 ID cookie。
我可以在泽西岛买到这个饼干。问题是当我想涉及 Retrofit2 和 OkHttp 时。
public interface Interceptor {
Response intercept(Chain chain) throws IOException;
interface Chain {
Request request();
Response proceed(Request request) throws IOException;
/**
* Returns the connection the request will be executed on. This is only available in the chains
* of network interceptors; for application interceptors this is always null.
*/
@Nullable Connection connection();
}
}
所以Request 需要包含User-Id
现在的问题是,我们如何让 OkHttp 从 Jersey 中获取这个 User-Id?
我们需要在发送到 RequestInterceptor 的时候进行同步。 我没有看到将东西注入 RequestInterceptor 的简单方法 因为它是 Okhttp。问题是 Jersey 是 Java 1900-2000,其中 Retrofit 和 OkHttp 就像 Java 2015+
所以在一个地方做到这一点User-Id 的唯一方法是使用RequestInterceptor
它是一个接口,必须共享,因此 User-Id 必须 somehome 来自 parameter 内部 intercept 函数而不是构造函数。
该参数需要有User-Id,这样我们就不必做ThreadLocal之类的讨厌的事情,或者同步。
更新:我做了一个示例项目:
https://github.com/andrewarrow/web-wash
如果您查看此文件:
目标是能够替换:
userClient.getSomething(user_id)
与
userClient.getSomething()
并让 userClient 在线程中自动神奇地获取 user_id 安全的方式。请记住:
https://github.com/andrewarrow/web-wash/blob/master/src/team/higher/web/client/UserClient.kt
@GET("user/test")
fun getSomething(@Header("User-Id") id: String): String
将使用@Header 中的 id 导致 OKHttp 和 Retrofit2 生成 URL 连接并将该 ID 放在该 http GET 的 http 标头中 到 api:
【问题讨论】:
标签: jersey retrofit retrofit2 dropwizard okhttp