開始之前先甩上retrofit和okhttp的github鏈接:
https://github.com/square/retrofit
https://github.com/square/okhttp
大家都知道一款A(yù)PP里請求很多纷捞,如果能統(tǒng)一打印請求與響應(yīng)的json自然十分方便凰盔。retrofit作為知名網(wǎng)絡(luò)請求框架昧港,提供了攔截器Interceptor褪子,官方對攔截器的定義:
Interceptors area powerful mechanism that can monitor, rewrite, and retry calls.
攔截器可以用來轉(zhuǎn)換,重試排龄,重寫請求的機制爽柒。
我們就不轉(zhuǎn)換重寫了,只是打印一下就好率挣。
先添加依賴:
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.google.code.gson:gson:2.6.1'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
compile 'com.orhanobut:logger:2.1.0' // 打印日志
其實okhttp已經(jīng)為我們提供了一個Interceptor的實現(xiàn)類:HttpLoggingInterceptor。只要稍作設(shè)置就可以:
HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
if(BuildConfig.DEBUG){
//顯示日志
logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
}else {
logInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
}
okHttpClient.addInterceptor(logInterceptor);
這樣請求和響應(yīng)的日志就都會打印出來啦~
但是有些手機比如聯(lián)想可能會默認(rèn)屏蔽這樣的日志(之前我就是用聯(lián)想手機測試露戒,還以為這方法不管用)椒功,可以在手機上設(shè)置使其顯示。不同的機器設(shè)置方式不一樣智什,搜索一下都有~
如果不想設(shè)置或者想自己定義一下打印的格式动漾,可以像下面這樣寫:
public class LoggingInterceptor implements Interceptor {
private final Charset UTF8 = Charset.forName("UTF-8");
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody requestBody = request.body();
String body = null;
if(requestBody != null) {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
body = buffer.readString(charset);
}
Logger.e("發(fā)送請求\nmethod:%s\nurl:%s\nheaders: %sbody:%s",
request.method(), request.url(), request.headers(), body);
long startNs = System.nanoTime();
Response response = chain.proceed(request);
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
String rBody = null;
if(HttpEngine.hasBody(response)) {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
e.printStackTrace();
}
}
rBody = buffer.clone().readString(charset);
}
Logger.e("收到響應(yīng) %s%s %ss\n請求url:%s\n請求body:%s\n響應(yīng)body:%s",
response.code(), response.message(), tookMs, response.request().url(), body, rBody);
return response;
}
}
在OkHttpClient中添加攔截:
OkHttpClient.Builder client = new OkHttpClient.Builder()
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)//設(shè)置超時時間
.retryOnConnectionFailure(true);
//添加攔截
if (BuildConfig.DEBUG) {
client.addInterceptor(new LoggingInterceptor())
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
看一些博客里的文章,好像直接通過下面的代碼就可以攔截響應(yīng)撩鹿,但是我這么寫了并沒有看到有日志輸出...除非像上面那樣重寫HttpLoggingInterceptor.Logger的log()方法谦炬,難道是其實打印了我沒找到?......有知道的小伙伴告知一下
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
----------------------------------------------2017-07-25----------------------------------------------
還真是其實打印了我沒找到节沦,見開頭键思。
參考:
Android Retrofit2.0查看log和JSON字符串(HttpLoggingInterceptor)
OkHttp使用(四)攔截器
https://github.com/jaydenxiao2016/AndroidFire
這里還有一篇:
HttpLoggingInterceptor攔截的log信息為unicode字符時的解決辦法