Cha*_*dru 13 android request okhttp jsonresponse retrofit2
在执行enque操作之前,我需要获取请求主体并使用Retrofit 2.0执行一些逻辑操作.但遗憾的是,我无法通过服务电话获取帖子正文内容.目前搜索了很多之后,我发现好像只有一个办法logging了request,我现在用的改造2.0可以发布该方法通过使用HttpLoggingInterceptor具有OkHttpClient.我使用以下代码在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);
Run Code Online (Sandbox Code Playgroud)
问题我面对上述方法:
02-04 01:35:59.235 5007-5035/com.example.retrofitdemo D/OkHttp:{"nameValuePairs":{"id":"1","name":"chandru","type":"user"}}
但是上面的方法只返回logcat中的响应体,我无法将其作为String或者JSONObject.尽管如果我能够使用响应体HttpLoggingInterceptor,我的请求体将一直显示在Logcat中,标签为"OkHttp",即使在应用程序进入生产之后也是如此(所以主要是这样一种解除帖子的方式logcat中的数据).
我的要求:
我需要在不对Logcat中的post数据进行修改的情况下将请求体作为String或者JSONObject任何方法获取.
我尝试了什么:
我试图获取请求正文,即使onResponse从以后Response<T> response,但我无法完成它可能.请找到我为此目的使用的代码,如下所示:
Gson gson = new Gson();
String responseString = gson.toJson(response.raw().request().body());
Run Code Online (Sandbox Code Playgroud)
注意:上述转换后的请求正文使用gson.toJson方法仅返回元数据而非请求发布数据.
请提供宝贵的提示和解决方案,帮助我解决这个问题.我不知道该怎么做.过去两天我完全坚持了这一点.如果我的问题太冗长,请原谅.欢迎你提出任何建议.如果我的要求不明确,请告诉我.提前致谢.
sil*_*udo 48
我已经从这个链接 Retrofit2:在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";
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用的改进依赖项
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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18890 次 |
| 最近记录: |