[英]retrofit 2.0 how to print the full json response?
I am moving from Volley to Retrofit currently version 2.0.我正在从 Volley 转向 Retrofit 当前版本 2.0。
How to print the the full json response code ?如何打印完整的 json 响应代码?
includes :包括:
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 : API服务:
@GET("my/json")
Call<Model> getFeed();
In Activity - Calling API :在活动中 - 调用 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());
}
});
To print the full response in json:要在 json 中打印完整的响应:
Log.w("2.0 getFeed > Full json res wrapped in gson => ",new Gson().toJson(response));
If you'd like to have pretty print feature, use:如果您想要漂亮的打印功能,请使用:
Log.w("2.0 getFeed > Full json res wrapped in pretty printed gson => ",new GsonBuilder().setPrettyPrinting().create().toJson(response));
Note that this prints the deserialized data (not raw response as returned from server).请注意,这会打印反序列化的数据(不是从服务器返回的原始响应)。 To get the raw response, you may use one of these:
要获得原始响应,您可以使用以下方法之一:
HttpLoggingInterceptor
see: https://stackoverflow.com/a/33256827/2267723 or have your own version of interceptorHttpLoggingInterceptor
请参阅: https : HttpLoggingInterceptor
或拥有自己的拦截器版本Stetho
.Stetho
。 see: http://facebook.github.io/stetho/ or Charles Web Debugging Proxy
.Charles Web Debugging Proxy
。 see: https://www.charlesproxy.comActually Square already create a class just for this, just add实际上 Square 已经为此创建了一个类,只需添加
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();
And, in Retrofit并且,在改造中
Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl("https://yourapi.com/api/")
.build();
The interceptor class is in maven central拦截器类位于 maven 中心
compile 'com.squareup.okhttp3:logging-interceptor:3.5.0'
You can set the logging level in HttpLoggingInterceptor class.您可以在 HttpLoggingInterceptor 类中设置日志记录级别。 BODY is the verbose one (it print everything to the Body).
BODY 是冗长的(它将所有内容打印到 Body)。 Further information is available on OkHttp github
更多信息可在OkHttp github上获得
Caution!警告!
Don't forget to remove Interceptors (or change Logging Level to NONE) in production!不要忘记在生产中删除拦截器(或将日志级别更改为 NONE)! Otherwise people will be able to see your request and response on Log Cat.
否则人们将能够在 Log Cat 上看到您的请求和响应。
Plug in the following interceptor class like this像这样插入下面的拦截器类
OkHttpClient client = new OkHttpClient();
client.interceptors().add(new LoggingInterceptor());
//////Interceptor class //////拦截器类
public static class LoggingInterceptor implements Interceptor {
@Override
public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
Log.i("LoggingInterceptor","inside intercept callback");
Request request = chain.request();
long t1 = System.nanoTime();
String requestLog = String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers());
if(request.method().compareToIgnoreCase("post")==0){
requestLog ="\n"+requestLog+"\n"+bodyToString(request);
}
Log.d("TAG","request"+"\n"+requestLog);
com.squareup.okhttp.Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseLog = String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers());
String bodyString = response.body().string();
Log.d("TAG","response only"+"\n"+bodyString);
Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
public static String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}`
Courtesy : https://github.com/square/retrofit/issues/1072#礼貌: https : //github.com/square/retrofit/issues/1072#
To get full response in Json in retrofit use below.要在下面的改造中使用 Json 获得完整响应。
this works for me.这对我有用。
call.enqueue(new Callback<someList>() {
@Override
public void onResponse(Call<someList> call, Response<someList> response) {
if (response.isSuccessful())
Log.e("Success", new Gson().toJson(response.body()));
else
Log.e("unSuccess", new Gson().toJson(response.errorBody()));
}
@Override
public void onFailure(Call<someList> call, Throwable t) {
Log.e("onFailure", t.toString());
}
});
You can setLogLevel
to your Retrofit
adapter like below, and see the response and other data such as header, response code vs.您可以像下面那样将
setLogLevel
为您的Retrofit
适配器,并查看响应和其他数据,例如标头、响应代码与响应。
setLogLevel(LogLevel.FULL)
If you're using Retrofit version 2+ you have to set OkHttpLoggingInterceptor
to see logs.如果您使用的是 Retrofit 版本 2+,则必须设置
OkHttpLoggingInterceptor
才能查看日志。
First add OkHttpLoggingInterceptor
to your project:首先将
OkHttpLoggingInterceptor
添加到您的项目中:
com.squareup.okhttp3:logging-interceptor:${Versions.okHttpLoggingInterceptorVersion}
And than create init your interceptor:然后创建 init 你的拦截器:
HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }
And finally add it to your OkHttpClient最后将其添加到您的 OkHttpClient
with(OkHttpClient.Builder()) {
if (BuildConfig.DEBUG) addInterceptor(loggingInterceptor)
build()
}
Try this !!尝试这个 !!
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
/** Handles Log */
retrofit.client().interceptors().add(new LoggingInterceptor());
mRestClient = retrofit.create(RestServices.class);
class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Logger.d(String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Logger.d(String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
final String responseString = new String(response.body().bytes());
Logger.d("Response: " + responseString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), responseString))
.build();
}
Log.e("TAG","2.0 getFeed > response.raw() => " + new Gson().toJson(response.body()));
public class HttpLoggingInterceptor {
HttpLoggingInterceptor provideHttpLoggingInterceptor(){
return new HttpLoggingInterceptor(message ->
Log.d("TAG", message)).setLevel(HttpLoggingInterceptor.Level.BODY);
}
}
public class OkHttpClient {
OkHttpClient provideOkHttpClient(@NonNull HttpLoggingInterceptor interceptor){
return new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
}
}
尝试这个 :
Log.d("LOG","RESPONSE ==="+response.raw().toString());
Take a look on okhttp3.logging package, they already have HttpLoggingInterceptor that you can use for your needs.看看 okhttp3.logging 包,他们已经有 HttpLoggingInterceptor 可以满足您的需求。 And depending on them you can also specify logging level.
根据它们,您还可以指定日志记录级别。
and you can include this interceptor to your request as mentioned - via OkHttpClient.Builder:并且您可以将这个拦截器包含在您的请求中 - 通过 OkHttpClient.Builder:
public OkHttpClient provideOkHttpClient() {
final OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
okHttpBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
return okHttpBuilder.build();
}
To get full json response with retrofit 2.0 follow code given below要使用改造 2.0 获得完整的 json 响应,请遵循下面给出的代码
@GET("my/json")
Call<JsonObject> getFeed();
Call<JsonObject> call = RestClient.get().getFeed();
call.enqueue(new Callback<JsonObject>() {
@Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
Log.d("res", response.body().toString());
}
@Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.d("error",t.getMessage());
}
});
Call<Model> call = RestClient.get().getFeed();call.enqueue(new Callbstrong
textack<Model>() {
@Override
public void onResponse(Response<Model> response, Retrofit retrofit) {
//try this
Call<Model> call = response.body();
// this is enough for retrieve model
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
og.e("2.0 getFeed > onFailure => ", t.toString());
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.