完美解决okhttp报java.lang.IllegalStat

2017-07-07  本文已影响714人  wodezhuanshu

目前的我的场景是:
使用拦截器全局验证token

 Request request = requestBuilder.build();
        Response originalResponse = chain.proceed(request);
        ResponseBody result = originalResponse.body();
        final MediaType mediaType = result.contentType();
        Log.e("HeaderInterceptor", "intercept: " + result);
        final String s = result.string();
        if (!validateToken(s)) {
            return null;
        } else {
            Log.e("HeaderInterceptor", "intercept: " + originalResponse);
//            return chain.proceed(request);
            return originalResponse.newBuilder().body(ResponseBody.create(mediaType,s)).build();
        }

上面的办法只是重新创建了ResponseBody 然后将服务器返回的数据重新填充进去 ,我们也可以通过下面的方法
绕过上面的坑

   ResponseBody responseBody = originalResponse.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }

        String bodyString = buffer.clone().readString(charset);

        LogUtil.debug("body---------->" + bodyString);

相关链接:https://juejin.im/entry/584144d0128fe1006c3cfb8f

https://stackoverflow.com/questions/28306524/consuming-one-shot-responsebody-from-okhttp-causes-issues-with-retrofit

HttpLoggingInterceptor.java

上一篇下一篇

猜你喜欢

热点阅读