1. 程式人生 > >Retrofit2列印 網路請求日誌

Retrofit2列印 網路請求日誌

在使用Retrofit時,如果我們需要列印網路請求的日誌(諸如請求地址,引數,耗時,請求返回結果),

一、我可以使用現有的日誌庫,如下:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

在使用時,新增如下程式碼:

//宣告日誌類
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
//設定日誌級別
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

//自定義OkHttpClient
OkHttpClient.Builder
okHttpClient = new OkHttpClient.Builder(); //新增攔截器 okHttpClient.addInterceptor(httpLoggingInterceptor); //建立並指定自定義的OkHttpClient Retrofit retrofit = new Retrofit.Builder().baseUrl("http://ip.taobao.com").addConverterFactory(GsonConverterFactory.create()).client(okHttpClient.build()).build(); //建立介面服務類 TaoBaoApiService taoBaoApiService = retrofit.create
(TaoBaoApiService.class);

這樣在我們的網路請求中便會有如下日誌列印。

六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log
資訊: --> GET http://ip.taobao.com/service/getIpInfo.php?ip=220.248.17.90 http/1.1
六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log
資訊: --> END GET
六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log
資訊: <-- 200
OK http://ip.taobao.com/service/getIpInfo.php?ip=220.248.17.90 (36ms) 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: Server: Tengine 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: Date: Fri, 24 Jun 2016 07:31:03 GMT 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: Content-Type: text/html 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: Transfer-Encoding: chunked 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: Connection: keep-alive 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: Vary: Accept-Encoding 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: X-Powered-By: PHP/5.4.31 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: {"code":0,"data":{"country":"\u4e2d\u56fd","country_id":"CN","area":"\u534e\u4e1c","area_id":"300000","region":"\u4e0a\u6d77\u5e02","region_id":"310000","city":"\u4e0a\u6d77\u5e02","city_id":"310100","county":"","county_id":"-1","isp":"\u8054\u901a","isp_id":"100026","ip":"220.248.17.90"}} 六月 24, 2016 3:31:04 下午 okhttp3.internal.Platform log 資訊: <-- END HTTP (290-byte body)

二、自定義日誌列印處理

如果列印的資料不符合要求,我們自定義列印資訊的內容和格式

這裡我們使用一個自定的,具體程式碼大致如下:

okHttpClient.addInterceptor(new Interceptor() {
    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        //獲得請求資訊,此處如有需要可以新增headers資訊
        Request request = chain.request();
        //新增Cookie資訊
        request.newBuilder().addHeader("Cookie","aaaa");
        //列印請求資訊
        syso("url:" + request.url());
        syso("method:" + request.method());
        syso("request-body:" + request.body());

        //記錄請求耗時
        long startNs = System.nanoTime();
        okhttp3.Response response;
        try {
            //傳送請求,獲得相應,
            response = chain.proceed(request);
        } catch (Exception e) {
            throw e;
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
        //列印請求耗時
        syso("耗時:"+tookMs+"ms");
        //使用response獲得headers(),可以更新本地Cookie。
        syso("headers==========");
        Headers headers = response.headers();
        syso(headers.toString());

        //獲得返回的body,注意此處不要使用responseBody.string()獲取返回資料,原因在於這個方法會消耗返回結果的資料(buffer)
        ResponseBody responseBody = response.body();

        //為了不消耗buffer,我們這裡使用source先獲得buffer物件,然後clone()後使用
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        //獲得返回的資料
        Buffer buffer = source.buffer();
        //使用前clone()下,避免直接消耗
        syso("response:" + buffer.clone().readString(Charset.forName("UTF-8")));
        return response;
    }
});

程式碼說明已添加註釋。需要額外說明一點就是syso函式只是做簡單列印,如下:

private static void syso(String msg) {
    System.out.println(msg);
}