这里使用Okhttp写了一个demo来监听网络请求过程中的一系列数据,包括当前网络类型、请求体、响应体大小,url,请求方式,当然还有本次核心获取域名解析时长,建立连接时长,保持连接时长,请求总时长这些数据。
一次网络请求经历了哪些过程
通过域名访问的方式来请求网络时,会经历下列过程:
1.DNS解析:通过域名服务器或者本地host将域名解析成ip地址
2.建立连接:三次握手
3.发送数据:通过GET/POST/PUT等方式将数据(header和body)发送给服务器,
4.接受数据:接受服务器返回数据:响应头和body
5.断开链接:四次挥手断开链接
OkHttp库实现了哪些网络请求过程的状态回调
OkhttpClient的Builder类可以调用eventListener设置EventListener,EventListener会进行回调如上图的各个事件节点。
所有方法为:
public abstract class EventListener {
public void callStart(Call call) {}
// 域名解析
public void dnsStart(Call call, String domainName) {}
public void dnsEnd(Call call, String domainName, List<InetAddress> inetAddressList) {}
// 开始连接
public void connectStart(call, route.socketAddress(), proxy){}
// 释放当前Transmitter的RealConnection
public void connectionReleased(Call call, Connection connection) {}
public void connectionAcquired(call, result){};
// 请求
public void requestHeadersStart(@NotNull Call call){}
public void requestHeadersEnd(@NotNull Call call, @NotNull Request request) {}
// 响应
public void requestBodyStart(@NotNull Call call) {}
public void requestBodyEnd(@NotNull Call call, long byteCount) {}
// 结束
public void callEnd(Call call) {}
// 失败
public void callFailed(Call call, IOException ioe) {}
}
流程解释:
1.callStart:一次请求开始了
2.dns:dns解析过程
3.connectStart: 开始建立连接了
4.secureConnect: 开始建立TSL安全链接
5.connectEnd: 链接建立结束:可能建立失败,失败后可以重试
6.requestHeaders:发送请求头
7.requestBody:发送请求body
8.responseHeaders:客户端接受响应头
9.responseBody:客户端接受响应body
10.connectionReleased:链接释放
11.callEnd:一次请求结束
添加日志拦截器获取请求体、响应体大小和响应内容:
class LoggingInterceptor : Interceptor {
private val byteCount = 1024 * 1024
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
//chain里面包含了request和response,按需获取
val request = chain.request()
val response = chain.proceed(request)
Log.v(HTTP, "(请求地址): ${request.url()}")
Log.v(HTTP, "请求方式: ${request.method()}")
if (request.body() == null) {
Log.v(HTTP, "(请求体大小): 0")
} else {
val requestBody = request.body()
Log.v(HTTP, "(请求体大小): ${requestBody?.contentLength()}")
}
val responseBody = response.peekBody(byteCount.toLong())
Log.v(HTTP, "(响应体大小): ${responseBody.contentLength()}")
Log.v(HTTP, "响应内容: ${responseBody.string()}")
return response
}
}
自定义EventListener获取各个数据:
import android.util.Log
import com.apus.networkmonitor.constants.Tags
import okhttp3.*
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Proxy
import java.util.concurrent.TimeUnit
/**
* @author: libo
* @date: 2023/4/26 09:38
* @Description: 监听okhttp请求,包括连接总时长和请求总时长
*/
open class CustomOkEventListener: EventListener() {
private var dnsStart: Long = 0 //dns开始解析时间
private var connectStart: Long = 0 //开始连接时间
private var callStart: Long = 0 //开始请求时间
private var connectAquire: Long = 0 //连接获取时间
override fun callStart(call: Call) {
Log.v(Tags.CALL, "callStart")
callStart = System.nanoTime()
}
override fun dnsStart(call: Call, domainName: String) {
Log.v(Tags.CALL, "dnsStart")
dnsStart = System.nanoTime()
}
override fun dnsEnd(call: Call, domainName: String, inetAddressList: MutableList<InetAddress>) {
Log.v(Tags.CALL, "dnsEnd")
var dnsEnd = System.nanoTime()
var duration = TimeUnit.NANOSECONDS.toMillis(dnsEnd - dnsStart)
Log.v(Tags.HTTP, "(域名解析时长): $duration ms")
}
override fun connectStart(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy) {
Log.v(Tags.CALL, "connectStart")
connectStart = System.nanoTime()
}
override fun connectEnd(
call: Call,
inetSocketAddress: InetSocketAddress,
proxy: Proxy,
protocol: Protocol?
) {
Log.v(Tags.CALL, "connectEnd")
connectAquire = System.nanoTime()
var duration = TimeUnit.NANOSECONDS.toMillis(connectAquire - connectStart)
Log.v(Tags.HTTP, "(建连时长): $duration ms")
}
override fun connectionAcquired(call: Call, connection: Connection) {
Log.v(Tags.CALL, "connectionAcquired")
}
override fun connectionReleased(call: Call, connection: Connection) {
Log.v(Tags.CALL, "connectionReleased")
var connectReleased = System.nanoTime()
var duration = TimeUnit.NANOSECONDS.toMillis(connectReleased - connectAquire)
Log.v(Tags.HTTP, "(连接保持时长): $duration ms")
}
override fun callEnd(call: Call) {
Log.v(Tags.CALL, "callEnd")
var callEnd = System.nanoTime()
var duration = TimeUnit.NANOSECONDS.toMillis(callEnd - callStart)
Log.v(Tags.HTTP, "(请求总时长): $duration ms")
}
override fun callFailed(call: Call, ioe: IOException) {
Log.v(Tags.CALL, "callFailed")
var callEnd = System.nanoTime()
var duration = TimeUnit.NANOSECONDS.toMillis(callEnd - callStart)
Log.v(Tags.HTTP, "(请求总时长): $duration ms")
}
}
时间的计算用的是System.nanoTime(),返回正在运行的Java虚拟机的高分辨率时间源的当前值,单位为纳秒。
最后,将CustomOkEventListener设置给okhttpClient:
val builder = OkHttpClient.Builder()
.retryOnConnectionFailure(true) //失败重连
.addInterceptor(LoggingInterceptor()) //日志拦截器
.eventListener(CustomOkEventListener()) //统计请求链路各时长
builder.build()
Dns解析时长或者自定义Dns,然后设置给okhttpclient:
class CustomDns: Dns {
override fun lookup(hostname: String?): MutableList<InetAddress> {
var start = System.nanoTime() //返回正在运行的Java虚拟机的当前值,高分辨率时间源,单位为纳秒
val lookup = Dns.SYSTEM.lookup(hostname) //操作系统查找域名
var end = System.nanoTime()
var duration = TimeUnit.NANOSECONDS.toMillis(end - start)
Log.v(Tags.HTTP, "dns_time_l(域名解析时长): $duration " + "ms")
return lookup
}
}