改造2-是否可以获取我正在发送和接收的JSON的大小? [英] Retrofit 2 - Is it possible to get the size of a JSON that I'm sending and receiving?
问题描述
我需要在Android应用程序上构建流量监控器,并且需要存储通过翻新发送和接收的所有json的大小.使用日志我可以看到它的实际大小,但是我没有找到获取此信息的方法,因此可以保存它.我也无法获得response.raw,因为它已经被解析为我的课程了.有什么办法可以做到这一点?
I need to build a traffic monitor on my Android app, and I need to have stored the size of all json that I'm sending and receiving through retrofit. Using log I can see the actual size of it, but I haven't find a way to get this information so I could save it. I can't get the response.raw either since it's already been parsed to my classes. Is there any way to achieve that?
将vadkou答案标记为最佳答案.
Marked vadkou answer as the best one.
我没有创建新的拦截器,而是传递了lamda表达式:
Instead of creating a new interceptor, I passed the lamda expression:
httpClient.addInterceptor( chain -> {
okhttp3.Request request = chain.request();
okhttp3.Response response = chain.proceed(request);
if(request.body()!=null) {
long requestLength = request.body().contentLength();
Log.e("SERVICE GENERATOR", " CONTENT LENGTH" + requestLength);
}
long responseLength = response.body().contentLength();
Log.e("SERVICE GENERATOR", " RESPONSE LENGTH" + responseLength);
return response;
});
推荐答案
Retrofit 2在内部使用OkHttp,您可以配置OkHttp,而不必像Vaiden的回答中那样通过在构建适配器时添加自定义拦截器来获取原始HTTP响应.如下:
Retrofit 2 uses OkHttp internally, and you could configure OkHttp without having to resort to getting raw HTTP response as in Vaiden's answer by adding a custom Interceptor while building an adapter as follows:
private Retrofit createRetrofit() {
return new Retrofit.Builder()
.baseUrl(END_POINT)
// .addConverterFactory(...)
// .addCallAdapterFactory(...)
.client(createClient())
.build();
}
private OkHttpClient createClient() {
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder();
okHttpClientBuilder.addInterceptor(createYourInterceptor());
return okHttpClientBuilder.build();
}
除其他外,Interceptor接口还允许您访问每个请求的请求正文.
The Interceptor interface among other things allows you to access request body for every request you make.
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// do what you want with request.body().contentLength();
return chain.proceed(request);
}
这篇关于改造2-是否可以获取我正在发送和接收的JSON的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!