美文网首页
完美解决okhttp报java.lang.IllegalStat

完美解决okhttp报java.lang.IllegalStat

作者: wodezhuanshu | 来源:发表于2017-07-07 18:04 被阅读714次

    目前的我的场景是:
    使用拦截器全局验证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

    相关文章

      网友评论

          本文标题:完美解决okhttp报java.lang.IllegalStat

          本文链接:https://www.haomeiwen.com/subject/vfdrhxtx.html