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

时间:2016-02-03 20:37:17

标签: android request okhttp retrofit2 jsonresponse

在执行enque操作之前,我需要获取请求主体并使用Retrofit 2.0执行某些逻辑操作。但遗憾的是,我无法通过服务电话获取帖子正文内容。目前经过大量搜索后,我发现只有一个解决方案,例如logging request我使用this method使用HttpLoggingInterceptorOkHttpClient使用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); 使用Retrofit 2.0。我使用以下代码在Android Logcat中记录请求正文:

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

问题我正面对上述方法:

  1. 请求正文仅在默认的Android Logcat上看到,如<​​/ li>

    String

    但是上面的方法只返回logcat中的响应主体,我无法将其作为JSONObjectHttpLoggingInterceptor获取。尽管如果我能够使用String获得响应主体,我的请求主体将显示在Logcat中,标签为&#34; OkHttp&#34;即使在应用程序进入生产之后,所有的时间总是如此(因此主要是这样可以缓解logcat中的帖子数据)。

    我的要求:

    我需要将请求正文作为JSONObjectonResponse或任何方法获取,而不会在Logcat中修改帖子数据。

    我尝试了什么:

    我尝试从Response<T> response Gson gson = new Gson(); String responseString = gson.toJson(response.raw().request().body()); 获取请求正文,但我无法完成此任务。请查找我为此目的使用的代码,如下所示:

    gson.toJson

    注意:上述使用this.add(panel)方法转换后的请求正文仅返回元数据而非请求发布数据。

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

2 个答案:

答案 0 :(得分:46)

我从这个链接开始工作了 Retrofit2: Modifying request body in OkHttp Interceptor

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'

答案 1 :(得分:0)

我也有类似的问题,我在改装中将JSON设置为@Body类型,因此namevaluepair出现在原始主体的前面,并且可以在拦截器内看到它。 即使我们记录/调试jsonObject.toString,我们也会在没有显示namevaluepair的情况下看到请求是正确的。

我做的是设置

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

并且在调用方法时我通过

将JSONObject转换为JsonObject
 new JsonParser().parse(model).getAsJsonObject();
相关问题