通过拦截器

时间:2018-04-05 16:35:33

标签: android retrofit2 rx-java2 okhttp okhttp3

我使用RxJava和Retrofit来执行OkHttp请求。我可以在Android Studio的网络分析器中看到我的请求被泄露,因为它们使AsyncTask线程保持活动状态。对它们没有响应,它们的大小为空。我可以在网络探查器的线程视图中看到原始请求,令牌请求,更新的请求。但最初的要求永远不会完成。

在极端情况下,例如在QA环境中,由于某种原因,令牌每分钟刷新一次,线程池变满,不再进行调用。我想我们可以根据需要多次调用chain.proceed,但我认为错误仍然存​​在于那里。这是拦截器代码:

private static okhttp3.Interceptor oauthInterceptor = chain -> {
    OAuthToken token = OAuthToken.getOAuthToken();
    long initialTokenCreated = token.getCreatedUtc();

    Request request = changeTokenInRequest(chain.request(), token);
    Response response = chain.proceed(request);
    boolean forceTokenRefresh = false;

    if (initialTokenCreated != token.getCreatedUtc()) {
        // Then the token has been updated since we started this request
        request = changeTokenInRequest(chain.request(), token);
        response = chain.proceed(request);
    }

    String jsonType = "application/json";
    if (!response.body().contentType().toString().contains(jsonType)) {
        forceTokenRefresh = true;
    }

    // 401: Forbidden, 403: Permission denied
    if (forceTokenRefresh || ((response.code() == 401 || response.code() == 403)
            && OAuthToken.getOAuthToken().getRefreshToken() != null)) {
        OAuthToken refreshedToken = refreshToken();
        if (refreshedToken == null) {
            // Then there was a problem refreshing the token
            return response;
        }
        // Recreate the request with the new access token
        request = changeTokenInRequest(chain.request(), refreshedToken);
        return chain.proceed(request);
    } else {
        return response;
    }
};

protected static okhttp3.Request changeTokenInRequest(Request request, OAuthTokenBase token) {
    Headers.Builder builder = request.headers().newBuilder().removeAll("Authorization");
    if (!TextUtils.isEmpty(token.getTokenType()) && !TextUtils.isEmpty(token.getAccessToken())) {
        builder = builder.add("Authorization", token.getTokenType() + " " + token.getAccessToken());
    }
    request = request.newBuilder().headers(builder.build()).build();
    return request;
}

这就是我打电话的方式:

public static Observable<ResultPaginatedReply<BasicUser>> getGroupsMembers(String type, String id, int page) {
    return getMsApiService().getGroupsMembers(type, id, page)
            .subscribeOn(Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR))
            .observeOn(AndroidSchedulers.mainThread());
}

1 个答案:

答案 0 :(得分:2)

事实证明,如果你不像我这样在OkHttp中使用Authenticator类,那么在刷新令牌时你必须手动关闭响应体。 @DallinDyer的评论帮助了我here

所以我添加了

            response.body().close();

在错误检查之后发现了。