华域联盟 Andriod Retrofit2日志拦截器的使用

Retrofit2日志拦截器的使用

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

打印内容: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日志使用鼠标中键进行选中
  Logger.t(AppConfigs.LOGGER_NET_TAG).json(buffer.clone().readString(charset))
  }
 return response
 }

}

在Application中进行初始化Logger

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相关依赖外还需要依赖

implementation 'com.orhanobut:logger:2.2.0'

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » Retrofit2日志拦截器的使用

转载请保留出处和原文链接:https://www.cnhackhy.com/106170.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

Android实现长图文截图功能实例代码

Delphi在Android下使用Java库的方法

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部