Android Retrofit通过OkHttp设置Interceptor拦截器统一打印请求报文及返回报文

我们先定义一个打印报文的拦截器,继承Interceptor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class LogInterceptor implements Interceptor {

private static final String TAG = LogInterceptor.class.getSimpleName();

@Override
public Response intercept(Chain chain) throws IOException {
Charset UTF8 = Charset.forName("UTF-8");

// 打印请求报文
Request request = chain.request();
RequestBody requestBody = request.body();
String reqBody = null;
if(requestBody != null) {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);

Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
reqBody = buffer.readString(charset);
}
Log.d(TAG, String.format("发送请求\nmethod:%s\nurl:%s\nheaders: %s\nbody:%s",
request.method(), request.url(), request.headers(), reqBody));

// 打印返回报文
// 先执行请求,才能够获取报文
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
String respBody = null;
if(responseBody != null) {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE);
Buffer buffer = source.buffer();

Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
e.printStackTrace();
}
}
respBody = buffer.clone().readString(charset);
}
Log.d(TAG, String.format("收到响应\n%s %s\n请求url:%s\n请求body:%s\n响应body:%s",
response.code(), response.message(), response.request().url(), reqBody, respBody));
return response;
}
}

Click and drag to move

然后通过OkHttp设置拦截器

1
2
3
4
5
6
7
8
9
10
11
private Retrofit getRetrofit() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new LogInterceptor())
.build();
return new Retrofit.Builder()
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(getBaseUrl())
.build();
}

Click and drag to move

打印出来的报文如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
06-01 14:36:35.223 16547-16593/com.him.hisapp D/HttpServiceImpl: 发送请求
method:POST
url:http://www.yeyuanxinyi.com:6666/api/YeYuanXinYi
headers: header1: headerValue1
header2: headerValue2
header3: headerValue3

body:{"user_name":"yeyuanxinyi","age":"28","class":"3"}
06-01 14:36:39.003 16547-16593/com.him.hisapp D/HttpServiceImpl: 收到响应
200 OK
请求url:http://110.86.9.67:8401/api/VipSelfCashRegister/GetSysUser
请求body:{"customerCode":"VIP","passWord":"666666","username":"00088"}
响应body:{"success":true,"message":null,"code":null,"data":{"user_name":"yeyuanxinyi","age":"28","class":"3"}}

Click and drag to move