我在我的 OkHttp 客户端上放置了以下拦截器:
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
Log.d("Response", response.body().string());
return response;
}
});
但是,这在 Retrofit 2 中表现不佳。似乎您只能从响应中读取一次流,这可能是导致异常的原因。我在想改造正在尝试解析日志已经解析的流。那么我该如何得到回应呢?我目前正在尝试调试一个非常讨厌和奇怪的格式错误的 json 异常。
这是异常堆栈跟踪:
07 - 28 10: 58: 21.575 22401 - 22529 / REDACTED E / AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: REDACTED, PID: 22401
java.lang.IllegalStateException: closed
at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java: 378)
at okio.Buffer.writeAll(Buffer.java: 956)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java: 92)
at okhttp3.ResponseBody.bytes(ResponseBody.java: 83)
at okhttp3.ResponseBody.string(ResponseBody.java: 109)
at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 90)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java: 160)
at okhttp3.RealCall.access$100(RealCall.java: 30)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java: 127)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java: 32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java: 1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java: 587)
at java.lang.Thread.run(Thread.java: 841)
我看到堆栈中有多个拦截器,但我只显式添加了一个,即引发异常的 on。
最佳答案
您正在使用拦截器中的响应正文,因此您将要创建一个新响应:
@Override public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
ResponseBody body = response.body();
String bodyString = body.string();
MediaType contentType = body.contentType();
Log.d("Response", bodyString);
return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
}
您可能还想查看 OkHttp 存储库中的日志拦截器:https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor
关于java - 当我尝试记录网络响应时,OKHttp 抛出非法状态异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38641565/