使用背景:
Retrofit2使用了自定义拦截器,自定义拦截器中拦截了Response,调用了string(),导致解析报错:
java.lang.IllegalStateException: closed
原因:
response.body().string() 只能请求一次,请求过后,就会关闭;再次调用response.body().string()就会报close异常。
解决方法:
重新创建builder,重新设置body内容;
public class AuthInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
MediaType mediaType = response.body().contentType();
String content = response.body().string(); // string()只能执行一次
return response.newBuilder()
.body(ResponseBody.create(mediaType, content))
.build();
}
}