android - OkHttp 拦截器 - 已经响应 "consumed"
android - OkHttp interceptor - response already "consumed"
我正在尝试使用此拦截器进行身份验证:
public class CustomInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = chain.proceed(request);
if (response shows expired token) {
// get a new token (I use a synchronous Retrofit call)
// create a new request and modify it accordingly using the new token
Request newRequest = request.newBuilder()...build();
// retry the request
return chain.proceed(newRequest);
}
// otherwise just pass the original response on
return response;
}
问题是我的检查(响应显示过期令牌)与状态无关,我需要检查实际响应(正文内容)。
因此在检查之后,响应是 "consumed" 并且任何准备正文的尝试都将失败。
我试过 "clone" 读取之前的响应缓冲区,例如:
public static String responseAsString(Response response ){
Buffer clonedBuffer = response.body().source().buffer().clone();
return ByteString.of(clonedBuffer.readByteArray()).toString();
}
但是它不起作用,clonedBuffer 是空的。
任何帮助将不胜感激。
我自己也遇到了同样的问题,我找到的解决方案是消耗响应的主体并用新的主体构建新的响应。我是这样做的:
...
Response response = chain.proceed(request);
MediaType contentType = response.body().contentType();
String bodyString = response.body().string();
if (tokenExpired(bodyString)) {
// your logic here...
}
ResponseBody body = ResponseBody.create(contentType, bodyString);
return response.newBuilder().body(body).build();
我正在尝试使用此拦截器进行身份验证:
public class CustomInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// try the request
Response response = chain.proceed(request);
if (response shows expired token) {
// get a new token (I use a synchronous Retrofit call)
// create a new request and modify it accordingly using the new token
Request newRequest = request.newBuilder()...build();
// retry the request
return chain.proceed(newRequest);
}
// otherwise just pass the original response on
return response;
}
问题是我的检查(响应显示过期令牌)与状态无关,我需要检查实际响应(正文内容)。 因此在检查之后,响应是 "consumed" 并且任何准备正文的尝试都将失败。
我试过 "clone" 读取之前的响应缓冲区,例如:
public static String responseAsString(Response response ){
Buffer clonedBuffer = response.body().source().buffer().clone();
return ByteString.of(clonedBuffer.readByteArray()).toString();
}
但是它不起作用,clonedBuffer 是空的。 任何帮助将不胜感激。
我自己也遇到了同样的问题,我找到的解决方案是消耗响应的主体并用新的主体构建新的响应。我是这样做的:
...
Response response = chain.proceed(request);
MediaType contentType = response.body().contentType();
String bodyString = response.body().string();
if (tokenExpired(bodyString)) {
// your logic here...
}
ResponseBody body = ResponseBody.create(contentType, bodyString);
return response.newBuilder().body(body).build();