0
点赞
收藏
分享

微信扫一扫

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

年夜雪 2022-02-27 阅读 70

背景

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

解决方案

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


添加依赖implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'添加拦截器 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. 打印出的日志样例:

打印完整的okhttp网络请求和响应消息_接口调用

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


点击关注专栏,查看最新技术分享

更多技术总结好文,请关注:「程序园中猿」

打印完整的okhttp网络请求和响应消息_接口调用_02打印完整的okhttp网络请求和响应消息_接口调用_03

举报

相关推荐

0 条评论