okhttp验证器取消请求

时间:2017-04-18 12:25:56

标签: android request retrofit okhttp

我正在尝试使用okHttp管理我的令牌过期。所以我在互联网上阅读了大量的回复,并建议将okHttp与Authenticator一起使用。所以我创建了一个验证器:

public class TokenAuthenticator implements Authenticator {

private Context mContext;
private RefreshToken mNewRefreshToken;

public TokenAuthenticator(Context context) {
    this.mContext = context;
}

@Override
public Request authenticate(Route route, final okhttp3.Response response) throws IOException {
    String refreshToken = SharedPreferenceHelper.getSharedPreferenceString(mContext, "refresh_token", null);
    APIService apiService = ServiceGenerator.createAuthenticatedService();
    Call<RefreshToken> call = apiService.refreshToken();
    retrofit2.Response<RefreshToken> responseCall = call.execute();

    // If success, we saved new token to SharedPref and redo a request to the server with new token
    if (responseCall.code() == 200) {
        mNewRefreshToken = responseCall.body();
        SharedPreferenceHelper.setSharedPreferenceString(mContext, "refresh_token", mNewRefreshToken.getRefreshToken());
        SharedPreferenceHelper.setSharedPreferenceString(mContext, "access_token", mNewRefreshToken.getAccessToken());
        return response.request().newBuilder()
                .header("Authorization", "Bearer " + mNewRefreshToken.getAccessToken())
                .build();
    }

    // If refreshToken expired, we logout
    if (responseCall.code() == 401) {
        //todo
        return null;
    }

    return null;
}
}

问题是偶数如果我返回null,它将再次执行新请求,即使请求无效。我想取消请求,但我还没有找到任何相关信息。有人有想法吗?

谢谢你

0 个答案:

没有答案