通過自定義OkHttp的 Interceptor 來實現
Interceptor可以在OkHttp的請求和響應中添加鞭缭、修改和刪除headers魏颓,以及做其他的一些操作
public class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// 在請求頭中添加log信息
request = request.newBuilder()
.header("log-info", "your log message here")
.build();
long t1 = System.nanoTime();
Log.d("OkHttp", String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.d("OkHttp", String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
}
在上面的例子中甸饱,我們創(chuàng)建了一個LoggingInterceptor類來攔截OkHttp的請求和響應,并在請求頭中添加了一個名為"log-info"的header柜候。你可以替換這個header的名字和值,來自定義你的log信息渣刷。
接下來,你可以將LoggingInterceptor添加到OkHttpClient中:
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();