Retrofit2日志拦截器的使用

2020-11-04 15:46:37 浏览数 (1)

显示样式如下,复制内容的时候使用鼠标中键进行选中

打印内容:code,请求方式,url,请求头,请求体,返回json

代码语言:javascript复制
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日志使用鼠标中键进行选中
  Logger.t(AppConfigs.LOGGER_NET_TAG).json(buffer.clone().readString(charset))
  }
 return response
 }

}

在Application中进行初始化Logger

代码语言:javascript复制
val strategy = PrettyFormatStrategy.newBuilder()
  .showThreadInfo(false) // 是否显示线程信息,默认为ture
  .methodCount(1)  // 显示的方法行数
  .methodOffset(0) // 隐藏内部方法调用到偏移量
  .tag("tag")
  .build()
 Logger.addLogAdapter(object : AndroidLogAdapter(strategy) {
  override fun isLoggable(priority: Int, tag: String?): Boolean {
  return BuildConfig.DEBUG
  }
 })

除了需要依赖Retrofit2相关依赖外还需要依赖

代码语言:javascript复制
implementation 'com.orhanobut:logger:2.2.0'

以上就是本文的全部内容,希望对大家的学习有所帮助。

0 人点赞