使用 Retrofit 2.0 POST 方法获取请求正文内容

Getting Request body content using Retrofit 2.0 POST method

在执行 enque 操作之前,我需要获取请求主体并使用 Retrofit 2.0 执行一些逻辑操作。但不幸的是,我无法从服务调用中获取 post 正文内容。目前,经过大量搜索后,我发现只有一个解决方案,例如 logging request 我正在 post 使用 this method 中的 Retrofit 2.0 通过使用 HttpLoggingInterceptorOkHttpClient。我正在使用以下代码在 Android Logcat:

中记录请求正文
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();  
       logging.setLevel(Level.BODY);
    OkHttpClient httpClient = new OkHttpClient();
    httpClient.interceptors().add(logging);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseURL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    return retrofit.create(apiClass);

我用上面的方法遇到的问题:

  1. 请求正文仅在默认 Android Logcat 上可见

02-04 01:35:59.235 5007-5035/com.example.retrofitdemo D/OkHttp:{"nameValuePairs":{"id":"1","name":"chandru","type":"user"}}

但是上面的方法returns只是在logcat中的响应体,我无法得到它作为StringJSONObject。尽管如果我能够使用 HttpLoggingInterceptor 获取响应主体,我的请求主体将一直显示在带有标签 "OkHttp" 的 Logcat 中,即使在应用程序进入生产后也是如此(因此,这主要导致了一种减轻 logcat 中的 post 数据的感觉。

我的要求:

我需要将请求正文作为 StringJSONObject 或任何方法获取,而不需要修改 Logcat.

中的 post 数据

我试过的:

即使在 onResponse 之后,我也尝试从 Response<T> response 获取请求正文,但我无法完成它。请找到我为此目的使用的代码如下:

 Gson gson = new Gson();
 String responseString =  gson.toJson(response.raw().request().body());

注意:上面使用gson.toJson方法转换的请求正文returns只有元数据而不是请求post数据。

请提供宝贵的提示和解决方案来帮助我解决这个问题。我不知道该怎么做。在过去的两天里,我完全坚持了这一点。如果我的问题太长,请原谅。欢迎你提出任何建议。如果我的要求不清楚,请告诉我。提前致谢。

我已经开始工作了 link

private String bodyToString(final RequestBody request) {
            try {
                final RequestBody copy = request;
                final Buffer buffer = new Buffer();
                if (copy != null)
                    copy.writeTo(buffer);
                else
                    return "";
                return buffer.readUtf8();
            } catch (final IOException e) {
                return "did not work";
            }
        }

我正在使用的改造依赖项是

 compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
    compile 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'

我也遇到了类似的问题,我在retrofit中设置了JSON为@Body类型,所以namevaluepair出现在raw body的前面,在拦截器内部可以看到。 即使我们 log/debug jsonObject.toString 我们认为请求是正确的,但没有提供名称值对。

我所做的是设置

Call<ResponseBody> getResults(@Body JsonObject variable);

在调用方法时,我通过

将JSON对象转换为JsonObject
 new JsonParser().parse(model).getAsJsonObject();