/**
* OkHttp的{@link Interceptor}, 通过设置
* {@link Configuration#enableLoggingNetworkParams()}打印网络请求参数与响应结果
*/
public class HttpLoggingInterceptor implements Interceptor {
private static final String TAG = "HttpLogging";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request(); // 获取请求
long t1 = System.nanoTime();
Buffer buffer = new Buffer();
request.body().writeTo(buffer); //获取请求体
Log.e(TAG, String.format("Sending request %s on %s%n%sRequest Params: %s",
request.url(), chain.connection(), request.headers(), buffer.clone().readUtf8()));
buffer.close();
Response response = chain.proceed(request); //执行请求
long t2 = System.nanoTime();
BufferedSource source = response.body().source(); //获取请求结果
source.request(Long.MAX_VALUE);
buffer = source.buffer().clone(); //克隆返回结果, 因为buffer只能使用一次
Log.e(TAG, String.format("Received response for %s in %.1fms%n%sResponse Json: %s",
response.request().url(), (t2 - t1) / 1e6d, response.headers(),
buffer.readUtf8()));
return response;
}
}
然后在RetrofitFactory中加入:
if (Configuration.isShowNetworkParams()) {
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(
new HttpLoggingInterceptor()).build();
builder.client(client);
}
以下是Log格式:
HttpLogging: Sending request http://xx.xx.xx.xx:xxxx/xxx/app/findAttractions.htm on null
Request Params: city=%E6%AD%A6%E6%B1%89&pageNo=1&pageSize=10&latitude=xxx&longitude=xxx
HttpLogging: Received response for http://xx.xx.xx.xx:xxxx/xxx/app/findAttractions.htm in 181.2ms
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 23 Mar 2016 06:50:48 GMT
OkHttp-Sent-Millis: 1458715847034
OkHttp-Received-Millis: 1458715847128
Response Json: {"data":{"attractionsList":[{"distance":13110.6,"id":13,"image":"xx.xx.xx.xx:xxxx/xxx/upload/201603171607138491.jpg","latitude":30.559024,"longitude":114.30341,"name":"黄鹤楼","profile":null,"score":5,"voice":"xx.xx.xx.xx:xxxx/xxx/upload/201603171009165109.mp3"}]},"msg":"成功","page":{"pageCount":1,"pageNo":1,"pageSize":10,"totalCount":1},"status":1}