Okhttp3: 使用拦截器Interceptor

设置拦截器

public class LoggingInterceptor implements Interceptor {
     

    @Override
    public Response intercept(Chain chain) throws IOException {
     
        Request request = chain.request();

        long startTime = System.nanoTime();
        log.info(String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        Response response =  chain.proceed(request);

        long endTime = System.nanoTime();
        log.info(String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (endTime - startTime) / 1e6d, response.headers()));

        return response;
    }
}

发起请求

在新建client时,addInterceptor

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(new LoggingInterceptor())
        .build();
Request request = new Request.Builder()
        .url("http://www.baidu.com")
        .header("User-Agent", "OkHttp Example")
        .build();
Response response = client.newCall(request).execute();

我们发起请求,可以看到以下打印结果:

Sending request http://www.baidu.com on null
User-Agent: OkHttp Example
        
Received response for http://www.baidu.com in 65.9ms
Cache-Control: private, no-cache, no-store, proxy-revalidate, no-transform
Connection: keep-alive
Content-Type: text/html
Date: Fri, 11 Sep 2020 07:01:37 GMT
Last-Modified: Mon, 23 Jan 2017 13:27:36 GMT
Pragma: no-cache
Server: bfe/1.0.8.18
Set-Cookie: BDORZ=27315; max-age=86400; domain=.baidu.com; path=/
Transfer-Encoding: chunked

拦截器已生效

你可能感兴趣的:(点点点工程师)