如何在 Android studio 中使用 retrofit2 获取 json 日志?

How to get json log using retrofit2 in Android studio?

我阅读 https://futurestud.io/blog/retrofit-2-log-requests-and-responses 并成功了。

    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);

    OkHttpClient client = new OkHttpClient();
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.interceptors().add(logging);

    client = builder.build();

    Retrofit retrofit = new Retrofit.Builder()
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(LoginApiService.Login_API_URL)
            .build();

但是它返回的结果像

09-08 05:12:24.219 25389-26089/com.example.keepair.myapplication D/OkHttp: --> POST http://ec2-52-78-138-143.ap-northeast-2.compute.amazonaws.com:8000/rest-auth/login/ http/1.1
09-08 05:12:24.219 25389-26089/com.example.keepair.myapplication D/OkHttp: Content-Type: application/json; charset=UTF-8
09-08 05:12:24.219 25389-26089/com.example.keepair.myapplication D/OkHttp: Content-Length: 46
09-08 05:12:24.219 25389-26089/com.example.keepair.myapplication D/OkHttp: --> END POST
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: <-- 400 Bad Request http://ec2-52-78-138-143.ap-northeast-2.compute.amazonaws.com:8000/rest-auth/login/ (96ms)
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: Date: Wed, 07 Sep 2016 20:11:27 GMT
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: Server: WSGIServer/0.2 CPython/3.4.3
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: Vary: Accept
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: Allow: POST, OPTIONS
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: X-Frame-Options: SAMEORIGIN
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: Content-Type: application/json
09-08 05:12:24.314 25389-26089/com.example.keepair.myapplication D/OkHttp: <-- END HTTP

不够。

因为我正在使用 RESTful api 和 json 类型,

  1. 我想检查 json 我发送给 api 的请求和来自 api 的 json 响应。例如,{ "hi" : "bye" },json 请求和响应的完整信息。
  2. 此外,我想确切地知道我的应用程序通过 header 发送了什么。

我该怎么办?

如果你看一下HttpLoggingInterceptor.setLevel的代码:

public HttpLoggingInterceptor setLevel(Level level) {
    if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
    this.level = level;
    return this;
}

您会发现每次调用此方法时都会覆盖上次调用,所以这样做:

logging.setLevel(HttpLoggingInterceptor.Level.BODY);
logging.setLevel(HttpLoggingInterceptor.Level.HEADERS);

将级别设置为 Level.HEADERS
这正是您的日志中发生的事情,您只看到 headers.
只需删除该(第二)行,您就会得到 Level.BODY,这就是您要查找的内容。