How to log request and response body with Retrofit-Android?

前端 未结 9 2061
盖世英雄少女心
盖世英雄少女心 2020-11-28 21:35

I can\'t find relevant methods in the Retrofit API for logging complete request/response bodies. I was expecting some help in the Profiler (but it only offers meta-data abou

9条回答
  •  抹茶落季
    2020-11-28 22:01

    There doesn't appear to be a way to do basic + body, but you can use FULL and filter the headers you don't want.

    RestAdapter adapter = new RestAdapter.Builder()
                              .setEndpoint(syncServer)
                              .setErrorHandler(err)
                              .setConverter(new GsonConverter(gson))
                              .setLogLevel(logLevel)
                              .setLog(new RestAdapter.Log() {
                                  @Override
                                  public void log(String msg) {
                                      String[] blacklist = {"Access-Control", "Cache-Control", "Connection", "Content-Type", "Keep-Alive", "Pragma", "Server", "Vary", "X-Powered-By"};
                                      for (String bString : blacklist) {
                                          if (msg.startsWith(bString)) {
                                              return;
                                          }
                                      }
                                      Log.d("Retrofit", msg);
                                  }
                              }).build();
    

    It appears that when overriding the log, the body is prefixed with a tag similar to

    [ 02-25 10:42:30.317 25645:26335 D/Retrofit ]
    

    so it should be easy to log basic + body by adjusting the custom filter. I am using a blacklist, but a whitelist could also be used depending on your needs.

提交回复
热议问题