如何让OkHttp从Jersey获取参数并在Interceptor中使用?

时间:2017-08-30 23:32:35

标签: jersey retrofit retrofit2 dropwizard okhttp

使用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从泽西岛获得这个用户ID?

我们发送到RequestInterceptor时需要同步它。 我没有看到将事情注入RequestInterceptor的简单方法 因为它是Okhttp。问题是泽西岛是Java 1900-2000,其中Retrofit和OkHttp就像Java 2015 +

所以在一个地方User-Id执行该操作的唯一方法是使用RequestInterceptor 它是一个接口,必须共享,因此User-Id必须来自parameter内部intercept函数,而不是来自构造函数。 该参数需要User-Id,因此我们不必做像ThreadLocal这样令人讨厌的事情,也不必同步。

更新:我制作了一个小型项目:

https://github.com/andrewarrow/web-wash

如果你看这个文件:

https://github.com/andrewarrow/web-wash/blob/master/src/team/higher/web/resource/DashboardResource.kt

目标是能够取代:

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:

https://api.github.com/user/test

1 个答案:

答案 0 :(得分:2)

  

用户ID必须来自拦截功能内的参数而不是来自构造函数。该参数需要具有User-Id,因此我们不必像ThreadLocal那样做讨厌的事情,或者同步。

使用代理有一点解决方法。使用Jersey,你可以做的是为用户id创建一个小包装器,然后让Jersey代理它。我们可以使用javax.inject.Provider来懒惰地检索拦截器中的用户。当我们这样做时,用户将被绑定到请求的上下文(这是有保证的,我们不需要担心管理我们自己的ThreadLocals或任何东西)。

public class UserIdInterceptor implements Interceptor {

    private final Provider<User> userProvider;

    UserIdInterceptor(Provider<User> userProvider) {
        this.userProvider = userProvider;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        final User user = userProvider.get();
        if (user.isValid()) {
            return chain.proceed(chain.request().newBuilder()
                    .addHeader("User-Id", userProvider.get().getName())
                    .build());
        } else {
            return chain.proceed(chain.request());
        }
    }
}

我们要做的是使用Jersey Factory在请求范围内创建User。这样,我们就可以为每个请求创建一个包含cookie的新用户。

public class UserFactory implements Factory<User> {

    @Inject
    private Provider<ContainerRequest> request;

    @Override
    public User provide() {
        Cookie cookie = request.get().getCookies().get("User-Id");
        return cookie != null
                ? new User(cookie.getValue())
                : new User(null);
    }
}

我们所做的还是为Retrofit创建工厂。这样我们可以将Provider<User>注入工厂并在构造时将其传递给拦截器。

public class RetrofitFactory implements Factory<Retrofit> {

    private final Retrofit retrofit;

    @Inject
    private RetrofitFactory(Provider<User> userProvider,
                            BaseUrlProvider urlProvider) {

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new UserIdInterceptor(userProvider))
                .build();

        this.retrofit = new Retrofit.Builder()
                .baseUrl(urlProvider.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }

    @Override
    public Retrofit provide() {
        return this.retrofit;
    }
}

然后在AbstractBinder

中将它们全部绑定在一起
@Override
public void configure() {
    bindFactory(RetrofitFactory.class)
            .to(Retrofit.class)
            .in(Singleton.class);

    bindFactory(UserFactory.class)
            .to(User.class)
            .in(RequestScoped.class)
            .proxy(true);

    bindFactory(ClientFactories.MessageClientFactory.class)
            .to(MessageClient.class);

    bind(new BaseUrlProvider(this.baseUrl))
            .to(BaseUrlProvider.class);
}

我在这个GitHub Repo

中整理了一个完整的演示
相关问题