Request request = new Request.Builder()
.url("http://example.com")
.post(RequestBody.create("foo",MediaType.get("text/plain")))
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//e.printStackTrace();
RequestBody b = call.request().body();
String t= b.toString(); ??? <-How would I get the original message?
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//do something
}
});
失败时,我试图保存我发送的原始消息。
我查看了函数,但似乎无法弄清楚如何获取我在回调中发送的原始消息。有没有办法让消息回来?
答案 0 :(得分:2)
如果有人正在寻找这个:
Buffer b = new Buffer();
call.request().body().writeTo(b)
String result=b.readString(Charset.defaultCharset()); //Change this to whatever your character set is
答案 1 :(得分:1)
除了您的回答之外,您还可以定义一个 Interceptor
并记录那些失败的请求。以此为例,不带任何条件:
class ReqInterceptor implements Interceptor
{
@Override
public Response intercept(Interceptor.Chain chain) throws IOException
{
Request request = chain.request(); // original Request
logger.info(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
logger.info(String.format("Received response for %s %s",
response.request().url(), response.headers()));
return response;
}
}
然后在客户端,类似:
OkHttpClient client = new OkHttpClient.Builder()
.addNetworkInterceptor(new ReqInterceptor()) //<--this
.build();
Request request = new Request.Builder()
.url("http://example.com")
.post(RequestBody.create("foo",MediaType.get("text/plain")))
.build();
Response response = client.newCall(request).execute();
response.body().close();
有两种类型,甚至 Interceptor
的 two defined implementations,但网络一种会提供通过线路传输的相同数据,因此如果需要确切信息,您可以选择此:>