Retrofit2日志拦截器的使用
程序员文章站
2022-05-27 10:25:51
显示样式如下,复制内容的时候使用鼠标中键进行选中
打印内容:code,请求方式,url,请求头,请求体,返回json
class loggerinterce...
显示样式如下,复制内容的时候使用鼠标中键进行选中
打印内容: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'
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。