Logging with Retrofit 2

前端 未结 21 1329
春和景丽
春和景丽 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:04

    Here is a simple way to filter any request/response params from the logs using HttpLoggingInterceptor :

    // Request patterns to filter
    private static final String[] REQUEST_PATTERNS = {
        "Content-Type",
    };
    // Response patterns to filter
    private static final String[] RESPONSE_PATTERNS = {"Server", "server", "X-Powered-By", "Set-Cookie", "Expires", "Cache-Control", "Pragma", "Content-Length", "access-control-allow-origin"};
    
    // Log requests and response
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
        @Override
        public void log(String message) {
    
            // Blacklist the elements not required
            for (String pattern: REQUEST_PATTERNS) {
                if (message.startsWith(pattern)) {
                    return;
                }
            }
            // Any response patterns as well...
            for (String pattern: RESPONSE_PATTERNS) {
                if (message.startsWith(pattern)) {
                    return;
                }
            }
            Log.d("RETROFIT", message);
        }
    });
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    

    Here is the full gist:

    https://gist.github.com/mankum93/179c2d5378f27e95742c3f2434de7168

提交回复
热议问题