aw4*_*w4y 16 android response interceptor okhttp
我正在尝试使用此拦截器进行身份验证:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题是我的检查(响应显示过期令牌)与状态无关,我需要检查实际响应(正文内容).因此,在检查之后,响应被"消耗"并且任何准备身体的尝试都将失败.
我试图在读取之前"克隆"响应缓冲区,如:
public static String responseAsString(Response response ){
Buffer clonedBuffer = response.body().source().buffer().clone();
return ByteString.of(clonedBuffer.readByteArray()).toString();
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用,clonedBuffer为空.任何帮助将不胜感激.
小智 26
我自己也遇到了同样的问题,我找到的解决方案是使用响应的主体并使用新的主体构建新的响应.我是这样做的:
...
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3573 次 |
| 最近记录: |