我需要在我的Android应用程序上构建一个流量监视器,我需要存储我通过改造发送和接收的所有json的大小.使用日志我可以看到它的实际大小,但我没有找到获取此信息的方法,所以我可以保存它.我无法获得response.raw,因为它已被解析为我的类.有没有办法实现这一目标?
编辑:标记的vadkou答案是最好的.
我没有创建一个新的拦截器,而是传递了lamda表达式:
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响应,如下所示:
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接口允许您为每个请求访问请求体.
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// do what you want with request.body().contentLength();
return chain.proceed(request);
}