【问题标题】:android - OkHttp interceptor - response already "consumed"android - OkHttp 拦截器 - 响应已经“消耗”
【发布时间】:2015-06-29 01:39:29
【问题描述】:

我正在尝试使用此拦截器进行身份验证:

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;
}

问题是我的检查(响应显示过期令牌)与状态无关,我需要检查实际响应(正文内容)。 因此,在检查之后,响应被“消耗”并且任何准备主体的尝试都将失败。

我尝试在读取之前“克隆”响应缓冲区,例如:

public static String responseAsString(Response response ){
    Buffer clonedBuffer = response.body().source().buffer().clone();
    return ByteString.of(clonedBuffer.readByteArray()).toString();
}

但它不起作用,cloneBuffer 是空的。 任何帮助将不胜感激。

【问题讨论】:

    标签: android response interceptor okhttp


    【解决方案1】:

    我自己也遇到了同样的问题,我找到的解决方案是消耗响应的主体并用新的主体构建新的响应。我是这样做的:

    ...
    
    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();
    

    【讨论】:

    • 可能是 MediaType contentType = response.body().contentType();?
    • 感谢 ResponseBody.create(contentType, bodyString);
    • 新的ResponseBody真的和原来的一样吗(除了正文,例如响应码、标头)?
    • 为此目的有一个名为peekBody 的新API。 github.com/square/okhttp/pull/2186
    猜你喜欢
    • 1970-01-01
    • 2017-07-03
    • 2020-09-18
    • 1970-01-01
    • 2015-04-16
    • 2021-09-01
    • 2020-01-17
    • 2019-12-28
    • 1970-01-01
    相关资源
    最近更新 更多