License
OKHttpLoggingInterceptor
A Pretty OkHttp Logging Interceptor:一款簡潔漂亮的OkHttp Logging攔截器,可以設置多個log打印等級,隨你心意,輸出你想要的
log。最好在OkHttp3.0以及更新版本使用,防止某些類找不到的問題
編譯:
compile 'com.ayvytr:OKHttpLoggingInterceptor:1.0.0'
使用:
1.添加OkHttp依賴
2.設置攔截器
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.STATE);
OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(interceptor)
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.build();
3. 而后,使用OkHttp進行Http連接,即可在Logcat中看到打印的日志。通過關鍵字"OkHttp"即可篩選攔截器log
詳細用法
設置警告
默認類型log,級別為Debug
LoggingInterceptor interceptor = new LoggingInterceptor();
log_default.jpg
警告級別log
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.ALL, LoggingInterceptor.Logger.WARN);
log_all.jpg
設置log打印類型
NONE:不打印log
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.NONE);
URL_BODY: 打印url和響應體
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.URL_BODY);
log_url_body.jpg
SINGLE: 打印Http狀態,url, 請求時長和響應體.
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.SINGLE);
log_single.jpg
STATE: 打印Http狀態和url
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.STATE);
log_state.jpg
HEADERS: 打印Http狀態,url,請求頭和響應頭
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.HEADERS);
log_headers.jpg
BODY: 打印Http狀態,url, 請求時長和響應體.
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.BODY);
log_body.jpg
ALL: 打印http狀態,url,請求時長,響應體,請求頭和響應頭
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.ALL);
log_all.jpg
下面就說說代碼咯
//獲取響應體字符串,進行了內容初步分析,當不可讀時/編碼過,返回響應常量字符串/嘗試獲取文件名,如果可讀,直接返回響應體(主要
希望log更友好一點)
private String getResponseBody(Request request, Response response) throws IOException
{
String body = "[No Response Body]";
if(HttpHeaders.hasBody(response))
{
ResponseBody responseBody = response.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
//如果是已經編碼的,直接返回這樣的常量字符串
if(isEncoded(request.headers()))
{
body = "[Body: Encoded]";
}
//如果不是我們可讀的內容
else if(!isPlaintext(buffer))
{
String url = request.url().toString();
//可能是文件,嘗試獲取文件名,比如圖片,http鏈接應該沒有附帶參數,這是直接獲取文件名
if(!url.contains("?"))
{
body = String.format("[File:%s]", url.substring(url.lastIndexOf("/") + 1));
}
//其他情況,直接提示不可讀
else
{
body = "[Body: Not readable]";
}
}
//直接返回響應體
else
{
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if(contentType != null)
{
charset = contentType.charset(UTF8);
}
body = buffer.clone().readString(charset);
}
}
return body;
}
用法到此結束,接下來到了最歡樂的推薦環節了:
- EasyAndroid:簡化Android開發的精品庫
- PrettyItemDecorations:RecyclerView分割線,以及微信聯系人右側字母索引效果
- Logger:極簡漂亮的日志打印庫,直接這樣用:L.e(msg),不用再設置tag啦!