License
OKHttpLoggingInterceptor
A Pretty OkHttp Logging Interceptor:一款簡潔漂亮的OkHttp Logging攔截器彬向,可以設(shè)置多個log打印等級逃片,隨你心意屡拨,輸出你想要的
log。最好在OkHttp3.0以及更新版本使用褥实,防止某些類找不到的問題
編譯:
compile 'com.ayvytr:OKHttpLoggingInterceptor:1.0.0'
使用:
1.添加OkHttp依賴
2.設(shè)置攔截器
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進(jìn)行Http連接,即可在Logcat中看到打印的日志损离。通過關(guān)鍵字"OkHttp"即可篩選攔截器log
詳細(xì)用法
設(shè)置警告
默認(rèn)類型log哥艇,級別為Debug
LoggingInterceptor interceptor = new LoggingInterceptor();
警告級別log
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.ALL, LoggingInterceptor.Logger.WARN);
設(shè)置log打印類型
NONE:不打印log
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.NONE);
URL_BODY: 打印url和響應(yīng)體
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.URL_BODY);
SINGLE: 打印Http狀態(tài),url, 請求時長和響應(yīng)體.
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.SINGLE);
STATE: 打印Http狀態(tài)和url
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.STATE);
HEADERS: 打印Http狀態(tài)僻澎,url貌踏,請求頭和響應(yīng)頭
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.HEADERS);
BODY: 打印Http狀態(tài),url, 請求時長和響應(yīng)體.
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.BODY);
ALL: 打印http狀態(tài)怎棱,url哩俭,請求時長绷跑,響應(yīng)體拳恋,請求頭和響應(yīng)頭
LoggingInterceptor interceptor = new LoggingInterceptor(LoggingLevel.ALL);
下面就說說代碼咯
//獲取響應(yīng)體字符串,進(jìn)行了內(nèi)容初步分析砸捏,當(dāng)不可讀時/編碼過谬运,返回響應(yīng)常量字符串/嘗試獲取文件名,如果可讀垦藏,直接返回響應(yīng)體(主要
希望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();
//如果是已經(jīng)編碼的梆暖,直接返回這樣的常量字符串
if(isEncoded(request.headers()))
{
body = "[Body: Encoded]";
}
//如果不是我們可讀的內(nèi)容
else if(!isPlaintext(buffer))
{
String url = request.url().toString();
//可能是文件,嘗試獲取文件名掂骏,比如圖片轰驳,http鏈接應(yīng)該沒有附帶參數(shù),這是直接獲取文件名
if(!url.contains("?"))
{
body = String.format("[File:%s]", url.substring(url.lastIndexOf("/") + 1));
}
//其他情況弟灼,直接提示不可讀
else
{
body = "[Body: Not readable]";
}
}
//直接返回響應(yīng)體
else
{
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if(contentType != null)
{
charset = contentType.charset(UTF8);
}
body = buffer.clone().readString(charset);
}
}
return body;
}
用法到此結(jié)束级解,接下來到了最歡樂的推薦環(huán)節(jié)了:
- EasyAndroid:簡化Android開發(fā)的精品庫
- PrettyItemDecorations:RecyclerView分割線,以及微信聯(lián)系人右側(cè)字母索引效果
- Logger:極簡漂亮的日志打印庫田绑,直接這樣用:L.e(msg)勤哗,不用再設(shè)置tag啦!
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者