欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Retrofit2日志攔截器的使用

 更新時間:2018年11月15日 08:34:48   作者:剛剛了然  
這篇文章主要介紹了Retrofit2日志攔截器的使用,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

顯示樣式如下,復(fù)制內(nèi)容的時候使用鼠標(biāo)中鍵進行選中

打印內(nèi)容:code,請求方式,url,請求頭,請求體,返回json

class LoggerInterceptor : Interceptor {
 override fun intercept(chain: Interceptor.Chain?): Response {
 val orgRequest = chain!!.request()
 val response = chain.proceed(orgRequest)
 val body = orgRequest.body()
 val sb = StringBuilder()
 if (orgRequest.method() == "POST" && body is FormBody) {
  val body1 = body
  for (i in 0 until body1.size()) {
  sb.append(body1.encodedName(i) + "=" + body1.encodedValue(i) + ",")
  }
  sb.delete(sb.length - 1, sb.length)
  //打印post請求的信息
  Logger.t(AppConfigs.LOGGER_NET_TAG).d("code=" + response.code() + "|method=" + orgRequest.method() + "|url=" + orgRequest.url()
   + "\n" + "headers:" + orgRequest.headers().toMultimap()
   + "\n" + "post請求體:{" + sb.toString() + "}")
 } else {
  //打印get請求的信息
  Logger.t(AppConfigs.LOGGER_NET_TAG).d("code=" + response.code() + "|method=" + orgRequest.method() + "|url=" + orgRequest.url()
   + "\n" + "headers:" + orgRequest.headers().toMultimap())
 }
 //返回json
 val responseBody = response.body()
 val contentLength = responseBody!!.contentLength()
  val source = responseBody.source()
  source.request(java.lang.Long.MAX_VALUE)
  val buffer = source.buffer()
  var charset = UTF8
  val contentType = responseBody.contentType()
  if (contentType != null) {
  try {
   charset = contentType.charset(UTF8)
  } catch (e: UnsupportedCharsetException) {
   return response
  }

  }
  if (contentLength != 0L) {
  //打印返回json
  //json日志使用鼠標(biāo)中鍵進行選中
  Logger.t(AppConfigs.LOGGER_NET_TAG).json(buffer.clone().readString(charset))
  }
 return response
 }

}

在Application中進行初始化Logger

val strategy = PrettyFormatStrategy.newBuilder()
  .showThreadInfo(false) // 是否顯示線程信息,默認(rèn)為ture
  .methodCount(1)  // 顯示的方法行數(shù)
  .methodOffset(0) // 隱藏內(nèi)部方法調(diào)用到偏移量
  .tag("tag")
  .build()
 Logger.addLogAdapter(object : AndroidLogAdapter(strategy) {
  override fun isLoggable(priority: Int, tag: String?): Boolean {
  return BuildConfig.DEBUG
  }
 })

除了需要依賴Retrofit2相關(guān)依賴外還需要依賴

implementation 'com.orhanobut:logger:2.2.0'

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論