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