当API返回错误响应时,我使用Okhttp3拦截器来刷新访问令牌(我使用的API很奇怪,并且还返回200以获取错误响应,所以我不确定使用Authenticator)。这是我的拦截器代码:
public class MyInterceptor implements Interceptor {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
String responseBodyString = response.body().string();
Response returnResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();
if(responseBodyString.contains("error")) {
DataDownloadManager.getInstance().downloadToken();
LogUtils.LOGE("Interceptor", "DownloadManager called");
Request newRequest = request.newBuilder().build();
LogUtils.LOGE("Interceptor", "new request dispatched");
return chain.proceed(newRequest);
}
else {
LogUtils.LOGE("Interceptor", "Outside");
return returnResponse;
}
}
}
这是我的DataDownloadManager:
public final class DataDownloadManager {
......
public static DataDownloadManager getInstance() {
if (instance == null) {
instance = new DataDownloadManager();
}
return instance;
}
public void downloadToken() {
try {
AccessToken accessToken = client.geteTouchesAPI().getAccessToken(APIUtils.ACCOUNT_ID, APIUtils.ACCOUNT_KEY)
.execute().body();
AccountUtils.setAccessToken(MyApplication.getAppContext(), accessToken.getToken());
} catch (IOException e) {
e.printStackTrace();
}
}
public void downloadSessionList() {
client.geteTouchesAPI().getSessionList(AccountUtils.getAccessToken(MyApplication.getAppContext()), APIUtils.EVENT_ID).enqueue(new Callback<List<SessionList>>() {
@Override
public void onResponse(Call<List<SessionList>> call, Response<List<SessionList>> response) {
if (response.isSuccessful()) {
for (SessionList sessionList : response.body()) {
LogUtils.LOGE(LOG_TAG, sessionList.getSessionId());
LogUtils.LOGE(LOG_TAG, sessionList.getSessionKey());
}
}
}
@Override
public void onFailure(Call<List<SessionList>> call, Throwable t) {
LogUtils.LOGE(LOG_TAG, t.toString());
}
});
}
}
这是我的Logcat:
07-15 20:17:12.530 29634-29992/com.my.app E/Interceptor: Outside
07-15 20:17:12.533 29634-29992/com.my.app E/AccountUtils:
Setting access token to: ....
07-15 20:17:12.534 29634-29992/com.my.app E/Interceptor:
DownloadManager called
07-15 20:17:12.534 29634-29992/com.my.app E/Interceptor: new
request dispatched
07-15 20:17:13.170 29634-29634/com.my.app
E/DataDownloadManager: java.lang.IllegalStateException: Expected
BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
我的初始调用是DataDownloadManager.getInstance().downloadSessionList()
,即使在错误响应之后,在logcat中也可以看到,请求不会再次执行。相反,返回初始失败的响应导致错误,如logcat的最后一行所示,不应该是这种情况。因为我正在重试错误请求,所以应该执行的唯一事情就是onResponse()
的{{1}}回调,而downloadSessionList()
执行,而且只执行一次(我的第二次执行)请求去?)。
我怀疑这是一个同步问题,但我无法确切地知道在哪里。