retrofit把gson解析都封装好了,url和response这些都变得不可见了,但是我们可以通过拦截的方式获取到,代码如下:
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request(); //Current Request
Response response = chain.proceed(originalRequest); //Get response of the request
/** DEBUG STUFF */
if (BuildConfig.DEBUG) {
//I am logging the response body in debug mode. When I do this I consume the response (OKHttp only lets you do this once) so i have re-build a new one using the cached body
String bodyString = response.body().string();
System.out.println(String.format("Sending request %s with headers %s ", originalRequest.url(), originalRequest.headers()));
System.out.println(String.format("Got response HTTP %s %s \n\n with body %s \n\n with headers %s ", response.code(), response.message(), bodyString, response.headers()));
response = response.newBuilder().body(ResponseBody.create(response.body().contentType(), bodyString)).build();
}
return response;
}
});
retrofit = new Retrofit.Builder()
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
其实就在okhttp里添加一个拦截器,把request和response 都输出出来
网友评论