Logging with Retrofit 2

前端 未结 21 1330
春和景丽
春和景丽 2020-11-22 07:33

I\'m trying to get the exact JSON that is being sent in the request. Here is my code:

OkHttpClient client = new OkHt         


        
21条回答
  •  抹茶落季
    2020-11-22 08:02

    For those who need high level logging in Retrofit, use the interceptor like this

    public static class LoggingInterceptor implements Interceptor {
        @Override public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            String requestLog = String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers());
            //YLog.d(String.format("Sending request %s on %s%n%s",
            //        request.url(), chain.connection(), request.headers()));
            if(request.method().compareToIgnoreCase("post")==0){
                requestLog ="\n"+requestLog+"\n"+bodyToString(request);
            }
            Log.d("TAG","request"+"\n"+requestLog);
    
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
    
            String responseLog = String.format("Received response for %s in %.1fms%n%s",
                    response.request().url(), (t2 - t1) / 1e6d, response.headers());
    
            String bodyString = response.body().string();
    
            Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);
    
            return response.newBuilder()
                    .body(ResponseBody.create(response.body().contentType(), bodyString))
                    .build();
            //return response;
        }
    }
    
    public static String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }`
    

    Courtesy: https://github.com/square/retrofit/issues/1072#

提交回复
热议问题