我正在从 Volley 迁移到当前版本 2.0 的 Retrofit。
如何打印完整的 json 响应码?
包括:
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
RestClient:
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
return response;
}
});
Gson gson = new GsonBuilder()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
REST_CLIENT = retrofit.create(APIService.class);
APIService:
@GET("my/json")
Call<Model> getFeed();
在 Activity 中 - 调用 API:
Call<Model> call = RestClient.get().getFeed();
call.enqueue(new Callback<Model>() {
@Override
public void onResponse(Response<Model> response, Retrofit retrofit) {
Log.w("2.0 getFeed > response.raw() => ", response.raw().toString());//DONT WORK
Log.w("2.0 getFeed > retrofit => ", retrofit.toString());//DONT WORK
Log.w("2.0 getFeed > body => ", response.body().toString()); //DONT WORK
Log.w("2.0 getFeed > getStatus => ", response.body().getStatus());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
Log.e("2.0 getFeed > onFailure => ", t.toString());
}
});
最佳答案
以 json 格式打印完整响应:
Log.w("2.0 getFeed > Full json res wrapped in gson => ",new Gson().toJson(response));
如果您想要 pretty-print 功能,请使用:
Log.w("2.0 getFeed > Full json res wrapped in pretty printed gson => ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
请注意,这会打印反序列化的数据(不是从服务器返回的原始响应)。要获得原始响应,您可以使用以下方法之一:
- 使用
HttpLoggingInterceptor
见:https://stackoverflow.com/a/33256827/2267723或者拥有自己的拦截器版本 - 使用 http 调试工具,例如
Stetho
。见:http://facebook.github.io/stetho/或Charles Web 调试代理
。见:https://www.charlesproxy.com
关于java - 改造 2.0 如何打印完整的 json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32965790/