欢迎访问宙启技术站
智能推送

Retrofit2日志拦截器的使用

发布时间:2023-05-16 06:28:06

Retrofit2是很多开发者都喜欢使用的HTTP客户端,在开发过程中,我们常常需要查看请求和响应的数据,以便于调试和排查问题。日志拦截器就是解决这个问题的利器。本文将详细介绍Retrofit2日志拦截器的使用。

### 一、如何添加日志拦截器

1. 导入依赖库:

implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'

2. 创建Retrofit实例时添加日志拦截器:

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://api.github.com/")
        .client(okHttpClient)
        .build();

其中addInterceptor方法中传入一个实例化的HttpLoggingInterceptor对象,并调用setLevel方法设置拦截的等级。HttpLoggingInterceptor具有如下Level级别:

- NONE:不记录日志

- BASIC:只记录请求方法,url,响应状态码和执行时间

- HEADERS:记录BASIC级别的所有信息,同时记录请求和响应头信息

- BODY:记录所有BASIC和HEADERS级别的信息,并记录请求和响应的正文内容

### 二、拦截器的使用

日志拦截器的使用非常简单,它会自动拦截我们发出的HTTP请求,并输出到控制台中,对于我们排查问题尤其方便。下面我们模拟一个简单的请求来看一下拦截器的输出信息:

@GET("getUserInfo")
Call<User> getUserInfo(@Query("userId") String userId);

Call<User> call = service.getUserInfo("1");
call.enqueue(new Callback<User>() {
    @Override
    public void onResponse(Call<User> call, Response<User> response) {
        if (response.isSuccessful()) {
            User user = response.body();
            Log.d(TAG, "onResponse: " + user.toString());
        } else {
            Log.d(TAG, "onResponse: " + response.errorBody().toString());
        }
    }

    @Override
    public void onFailure(Call<User> call, Throwable t) {
        Log.e(TAG, "onFailure: ", t);
    }
});

那么我们会得到如下的日志输出:

D/OkHttp: --> GET http://api.github.com/getUserInfo?userId=1 HTTP/1.1
D/OkHttp: --> END GET
D/OkHttp: <-- 200 OK http://api.github.com/getUserInfo?userId=1 (4ms)
D/OkHttp: Content-Type: application/json; charset=utf-8
D/OkHttp: Content-Length: 121
D/OkHttp: Connection: keep-alive
D/OkHttp: Server: GitHub.com
D/OkHttp: ETag: W/"791a143e6a1be250a7c3b9b540f2461c"
D/OkHttp: Cache-Control: max-age=0, private, must-revalidate
D/OkHttp: X-RateLimit-Limit: 60
D/OkHttp: X-RateLimit-Remaining: 57
D/OkHttp: X-RateLimit-Reset: 1653989602
D/OkHttp: X-OAuth-Scopes: read:user
D/OkHttp: X-Accepted-OAuth-Scopes: read:user
D/OkHttp: Vary: Accept-Encoding
D/OkHttp: X-GitHub-Media-Type:
D/OkHttp: Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
D/OkHttp: X-Content-Type-Options: nosniff
D/OkHttp: Content-Encoding: gzip
D/OkHttp: Date: Fri, 28 May 2021 07:39:25 GMT
D/OkHttp: Keep-Alive: timeout=60
D/OkHttp: X-GitHub-Request-Id: 5037:1BBB:B515B2:4E1F9F:60B0F3AD
D/OkHttp: {
D/OkHttp:   "code": 200,
D/OkHttp:   "msg": "success",
D/OkHttp:   "data": {
D/OkHttp:     "userId": "1",
D/OkHttp:     "userName": "张三",
D/OkHttp:     "userAge": 18
D/OkHttp:   }
D/OkHttp: }
D/OkHttp: <-- END HTTP (121-byte body)
D/MainActivity: onResponse: User{userId='1', userName='张三', userAge=18}

我们可以看到,拦截器成功记录了请求和响应的相关信息,而且输出得非常清晰易懂。

### 三、小结

本篇文章主要介绍了Retrofit2中日志拦截器的使用,通过添加日志拦截器,我们可以很方便地查看HTTP请求和响应的相关信息。在开发过程中,适时使用日志拦截器能够帮助我们快速定位问题并进行调试。