retrofit 基于okhttp炉菲。使用retrofit /okhttp時候,這些都會wifi
直連的默刚,不走系統(tǒng)的wifi設(shè)置,代理是抓不到包的逃魄。所以如果
想抓包那么抓網(wǎng)卡吧荤西,打印請求或者添加公共參數(shù)或者簽名之類的話,可以使用攔截器來添加伍俘。
攔截器這里使用okhttp的應(yīng)用攔截器邪锌,分別對get post添加統(tǒng)一參數(shù)和簽名
首先實現(xiàn) interceptor創(chuàng)建自己的攔截器
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addNetworkInterceptor(new LoggingInterceptor());
private static class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
//這個chain里面包含了request和response,所以你要什么都可以從這里拿
Request request = chain.request();
long t1 = System.nanoTime();//請求發(fā)起的時間
DebugLog.i(String.format(Locale.CHINA, "發(fā)送請求 %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();//收到響應(yīng)的時間
ResponseBody responseBody = response.peekBody(1024 * 1024);
//這里不能直接使用response.body().string()的方式輸出日志
//因為response.body().string()之后癌瘾,response中的流會被關(guān)閉觅丰,程序會報錯,我們需要創(chuàng)建出一
//個新的response給應(yīng)用層處理
DebugLog.i(String.format(Locale.CHINA, "接收響應(yīng): [%s] %n返回json:【%s】 %.1fms%n%s",
response.request().url(),
responseBody.string(),
(t2 - t1) / 1e6d,
response.headers()));
return response;
}
}