您当前的位置: 首页 >  网络

蓝不蓝编程

暂无认证

  • 0浏览

    0关注

    706博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

打印完整的okhttp网络请求和响应消息

蓝不蓝编程 发布时间:2018-11-30 11:14:57 ,浏览量:0

背景

开发中,有时需要核对接口请求和响应参数,需要看到详细的接口调用。本来可以通过Facebook Stetho来监控接口的,但是受限于网络,导致调测界面打不开,所以只要寻求其他方案。

解决方案

通过okhttp添加拦截器,打印接口调用日志。

  1. 添加依赖 implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
  2. 添加拦截器 HttpLogInterceptor.java
class HttpLogInterceptor : Interceptor {
    private val TAG = HttpLogInterceptor::class.java.simpleName
    private val UTF8 = Charset.forName("UTF-8")

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val requestBody = request.body()
        var body: String? = null
        requestBody?.let {
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            var charset: Charset? = UTF8
            val contentType = requestBody.contentType()
            contentType?.let {
                charset = contentType.charset(UTF8)
            }
            body = buffer.readString(charset!!)
        }

        Log.d(TAG,
                "发送请求: method:" + request.method()
                        + "\nurl:" + request.url()
                        + "\n请求头:" + request.headers()
                        + "\n请求参数: " + body)

        val startNs = System.nanoTime()
        val response = chain.proceed(request)
        val tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs)

        val responseBody = response.body()
        val rBody: String

        val source = responseBody!!.source()
        source.request(java.lang.Long.MAX_VALUE)
        val buffer = source.buffer()

        var charset: Charset? = UTF8
        val contentType = responseBody.contentType()
        contentType?.let {
            try {
                charset = contentType.charset(UTF8)
            } catch (e: UnsupportedCharsetException) {
                Log.e(TAG,e.message)
            }
        }
        rBody = buffer.clone().readString(charset!!)

        Log.d(TAG,
                "收到响应: code:" + response.code()
                        + "\n请求url:" + response.request().url()
                        + "\n请求body:" + body
                        + "\nResponse: " + rBody)

        return response
    }
}

添加拦截器(该拦截器需要最后添加,否则其他对request、response做修改的Interceptor所导致的变更就无法打印出来的。):

okBuilder.addInterceptor(HttpLogInterceptor())
  1. 打印出的日志样例:

  2. 如果想要格式化输出的消息格式,可以参考《利用logger打印完整的okhttp网络请求和响应日志》

安卓开发技术分享: https://blog.csdn.net/yinxing2008/article/details/84555061 点击关注专栏,查看最新技术分享 更多技术总结好文,请关注:「程序园中猿」

关注
打赏
1639405877
查看更多评论
立即登录/注册

微信扫码登录

0.0406s