Closed mathieudebrito closed 9 years ago
Hi,
I'm using an interceptor, and I would like to log the body of a request I'm making but I can't see any way of doing this.
Is it possible ?
public class LoggingInterceptor implements Interceptor { private static final String F_BREAK = " %n"; private static final String F_URL = " %s"; private static final String F_TIME = " in %.1fms"; private static final String F_HEADERS = F_BREAK + "%s"; private static final String F_RESPONSE = F_BREAK + " " + F_BREAK + "Response: %d" + F_BREAK; private static final String F_BODY = F_BREAK + "body: %s"; private static final String F_REQUEST_WITHOUT_BODY = F_URL + F_TIME + F_HEADERS; private static final String F_RESPONSE_WITHOUT_BODY = F_RESPONSE + F_HEADERS; private static final String F_REQUEST_WITH_BODY = F_URL + F_TIME + F_HEADERS + F_BODY; private static final String F_RESPONSE_WITH_BODY = F_RESPONSE + F_HEADERS + F_BODY; @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); long t1 = System.nanoTime(); Response response = chain.proceed(request); long t2 = System.nanoTime(); double time = (t2 - t1) / 1e6d; if (request.method().equals("GET")) { Logs.info(String.format("GET " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), response.code(), response.headers(), response.body().charStream())); } else if (request.method().equals("POST")) { Logs.info(String.format("POST " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body(), response.code(), response.headers(), response.body().charStream())); } else if (request.method().equals("PUT")) { Logs.info(String.format("PUT " + F_REQUEST_WITH_BODY + F_RESPONSE_WITH_BODY, request.url(), time, request.headers(), request.body().toString(), response.code(), response.headers(), response.body().charStream())); } else if (request.method().equals("DELETE")) { Logs.info(String.format("DELETE " + F_REQUEST_WITHOUT_BODY + F_RESPONSE_WITHOUT_BODY, request.url(), time, request.headers(), response.code(), response.headers())); } return response; } }
and the result :
POST [some url] in 88,7ms ZoneName: touraine Source: Android body: retrofit.client.OkClient$1@1df53f05 <-request.body().toString() gives me this, but I would like the content string Response: 500 Date: Tue, 24 Feb 2015 10:14:22 GMT Server: Apache/2.2.22 (Debian) Vary: Cookie,Accept-Encoding X-Frame-Options: SAMEORIGIN Connection: close Content-Type: text/html X-Pad: avoid browser bug OkHttp-Selected-Protocol: http/1.1 OkHttp-Sent-Millis: 1424772862181 OkHttp-Received-Millis: 1424772862250 body: [some content]
This is a question better suited for stack overflow. Please ask over there and tag okhttp.
Hi,
I'm using an interceptor, and I would like to log the body of a request I'm making but I can't see any way of doing this.
Is it possible ?
and the result :