Android okhttp 网络链接各阶段监控

news/2024/12/25 20:43:59/

步骤 1: 添加依赖

在项目的 build.gradle 文件中,添加 OkHttp 依赖:

implementation 'com.squareup.okhttp3:okhttp:4.11.0'

步骤 2: 创建自定义的 EventListener

创建一个自定义的 EventListener 类:

import android.util.Log
import okhttp3.*
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.Proxyclass LoggingEventListener : EventListener() {private var mCallStartTime: Long? = nullprivate var mCallEndTime: Long? = nullprivate var mDnsStartTime: Long? = nullprivate var mDnsEndTime: Long? = nullprivate var mConnectStartTime: Long? = nullprivate var mSecureConnectStartTime: Long? = nullprivate var mSecureConnectEndTime: Long? = nullprivate var mConnectEndTime: Long? = nullprivate var mRequestHeadersStartTime: Long? = nullprivate var mRequestHeadersEndTime: Long? = nullprivate var mResponseHeadersStartTime: Long? = nullprivate var mResponseHeadersEndTime: Long? = nullprivate var mResponseBodyStartTime: Long? = nullprivate var mResponseBodyEndTime: Long? = nullcompanion object {const val TAG = "LoggingEventListener"}override fun callStart(call: Call) {mCallStartTime = System.currentTimeMillis()Log.i(TAG, "Event callStart at $mCallStartTime")}override fun dnsStart(call: Call, domainName: String) {mDnsStartTime = System.currentTimeMillis()Log.i(TAG, "Event dnsStart at $mDnsStartTime")}override fun dnsEnd(call: Call, domainName: String, inetAddressList: List<InetAddress>) {mDnsEndTime = System.currentTimeMillis()Log.i(TAG, "Event dnsEnd at $mDnsEndTime dnsDuration is ${mDnsEndTime!! - mDnsStartTime!!} ms")}override fun connectStart(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy) {mConnectStartTime = System.currentTimeMillis()Log.i(TAG, "Event connectStart at $mConnectStartTime")}override fun secureConnectStart(call: Call) {mSecureConnectStartTime = System.currentTimeMillis()Log.i(TAG, "Event secureConnectStart at $mSecureConnectStartTime")}override fun secureConnectEnd(call: Call, handshake: Handshake?) {mSecureConnectEndTime = System.currentTimeMillis()Log.i(TAG, "Event secureConnectEnd at $mSecureConnectEndTime secureConnectDuration is ${mSecureConnectEndTime!! - mSecureConnectStartTime!!} ms")}override fun connectEnd(call: Call, inetSocketAddress: InetSocketAddress, proxy: Proxy, protocol: Protocol?) {mConnectEndTime = System.currentTimeMillis()Log.i(TAG, "Event connectEnd at $mConnectEndTime ConnectDuration is ${mConnectEndTime!! - mConnectStartTime!!} ms")}override fun requestHeadersStart(call: Call) {mRequestHeadersStartTime = System.currentTimeMillis()Log.i(TAG, "Event requestHeadersStart at $mRequestHeadersStartTime")}override fun requestHeadersEnd(call: Call, request: Request) {mRequestHeadersEndTime = System.currentTimeMillis()Log.i(TAG, "Event requestHeadersEnd at $mRequestHeadersEndTime requestHeadersDuration is ${mRequestHeadersEndTime!! - mRequestHeadersStartTime!!} ms")}override fun responseHeadersStart(call: Call) {mResponseHeadersStartTime = System.currentTimeMillis()Log.i(TAG, "Event responseHeadersStart at $mResponseHeadersStartTime")}override fun responseHeadersEnd(call: Call, response: Response) {mResponseHeadersEndTime = System.currentTimeMillis()Log.i(TAG, "Event responseHeadersEnd at $mResponseHeadersEndTime responseHeadersDuration is ${mResponseHeadersEndTime!! - mResponseHeadersStartTime!!} ms")}override fun responseBodyStart(call: Call) {mResponseBodyStartTime = System.currentTimeMillis()Log.i(TAG, "Event responseBodyStart at $mResponseBodyStartTime")}override fun responseBodyEnd(call: Call, byteCount: Long) {mResponseBodyEndTime = System.currentTimeMillis()Log.i(TAG, "Event responseBodyEnd at $mResponseBodyEndTime responseHeadersDuration is ${mResponseBodyEndTime!! - mResponseBodyStartTime!!} ms")}override fun callEnd(call: Call) {mCallEndTime = System.currentTimeMillis()Log.i(TAG, "Event callEnd at $mCallEndTime responseHeadersDuration is ${mCallEndTime!! - mCallStartTime!!} ms")}override fun callFailed(call: Call, ioe: IOException) {Log.i(TAG,"Request Failed: ${ioe.message}")}
}

步骤 3: 在 MainActivity 中发起网络请求

创建一个简单的 MainActivity,发起 HTTP 请求并使用 LoggingEventListener

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import okhttp3.*
import java.io.IOExceptionclass MainActivity : AppCompatActivity() {companion object {const val TAG = "MainActivity"}override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)// 创建 OkHttpClient 并设置自定义 EventListenerval client = OkHttpClient.Builder().eventListener(LoggingEventListener()).build()// 创建请求对象val request = Request.Builder().url("https://jsonplaceholder.typicode.com/posts/1") // 示例 API.build()// 发起异步网络请求client.newCall(request).enqueue(object : Callback {override fun onFailure(call: Call, e: IOException) {Log.i(TAG, "Request Failed: ${e.message}")}override fun onResponse(call: Call, response: Response) {Log.i(TAG, "Response: ${response.body?.string()}")}})}
}

步骤 4: 添加权限

AndroidManifest.xml 中添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

步骤 5: 布局文件

创建简单的布局文件 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"android:gravity="center"android:padding="16dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="OkHttp EventListener Demo"android:textSize="18sp"android:textStyle="bold" />
</LinearLayout>

运行结果

运行应用后,打开日志工具(Logcat)可以看到网络请求的各个阶段日志,例如:

I/LoggingEventListener: Event callStart at 1731855030207
I/LoggingEventListener: Event dnsStart at 1731855030212
I/LoggingEventListener: Event dnsEnd at 1731855030213 dnsDuration is 1 ms
I/LoggingEventListener: Event connectStart at 1731855030215
I/LoggingEventListener: Event secureConnectStart at 1731855030581
I/LoggingEventListener: Event secureConnectEnd at 1731855030878 secureConnectDuration is 297 ms
I/LoggingEventListener: Event connectEnd at 1731855030886 ConnectDuration is 671 ms
I/LoggingEventListener: Event requestHeadersStart at 1731855030887
I/LoggingEventListener: Event requestHeadersEnd at 1731855030889 requestHeadersDuration is 2 ms
I/LoggingEventListener: Event responseHeadersStart at 1731855031406
I/LoggingEventListener: Event responseHeadersEnd at 1731855031406 responseHeadersDuration is 0 ms
I/LoggingEventListener: Event responseBodyStart at 1731855031414
I/LoggingEventListener: Event responseBodyEnd at 1731855031415 responseHeadersDuration is 1 ms
I/LoggingEventListener: Event callEnd at 1731855031415 responseHeadersDuration is 1208 ms


http://www.ppmy.cn/news/1557803.html

相关文章

Firefox 基本设置备忘

Firefox 基本设置备忘 记录一些常用的 Firefox 设置&#xff0c;可以帮助增强浏览体验&#xff1a; 标签页设置: browser.search.openintab: true 在搜索栏中搜索时&#xff0c;在新标签页中打开结果。browser.tabs.loadBookmarksInTabs: true 点击书签时&#xff0c;在新标…

Arm Cortex-M处理器对比表

Arm Cortex-M处理器对比表 当前MCU处理器上主要流行RISC-V和ARM处理器&#xff0c;其他的内核相对比较少&#xff1b;在这两种内核中&#xff0c;又以Arm Cortex-M生态环境相对健全&#xff0c;大部分的厂家都在使用ARM的处理器。本文主要介绍Arm Cortex-M各个不同系列的参数对…

leetcode hot100 合并区间

56. 合并区间 已解答 中等 相关标签 相关企业 以数组 intervals 表示若干个区间的集合&#xff0c;其中单个区间为 intervals[i] [starti, endi] 。请你合并所有重叠的区间&#xff0c;并返回 一个不重叠的区间数组&#xff0c;该数组需恰好覆盖输入中的所有区间 示例 …

Android Java Ubuntu系统如何编译出 libopencv_java4.so

Cmake: cd ~ wget https://github.com/Kitware/CMake/releases/download/v3.30.3/cmake-3.30.3-linux-x86_64.tar.gztar -xzvf cmake-3.30.3-linux-x86_64.tar.gz sudo ln -sf $(pwd)/cmake-3.30.3-linux-x86_64/bin/* /usr/bin/cmake --versionAndroid NDK: wget https://…

一文了解 gis 相关服务=》及前端地图服务相关总结

文章目录 概要OGC技术名词解释cesium 应用案例openlayers 中应用实例XYZ服务OSM服务WMS服务WMTS服务WFS服务 mapbox 应用实例矢量瓦片服务栅格瓦片服务WMS服务WFS服务 leaflet 中 地图服务实例加载OpenStreetMap瓦片图层加载自定义XYZ瓦片图层加载WMS服务图层加载WFS服务图层加…

[机器学习]XGBoost(1)——前置知识

XGBoost简介 XGBoost&#xff08;eXtreme Gradient Boosting&#xff09;是一种一种高效的梯度提升决策树算法&#xff0c;它通过集成多个弱学习器&#xff08;决策树&#xff09;来构建一个强学习器。 核心思想&#xff1a; XGBoost的核心思想是Boosting&#xff0c;即通过…

《操作系统真象还原》第十章(一) —— 同步机制之互斥锁的实现

本章节所有代码托管在miniOS_32 章节任务介绍 问题复现 在上一节中&#xff0c;我们实现了线程轮转调度&#xff0c;并分别实现了三个线程并发的在终端进行输出打印 主线程 thread_work_a thread_work_b #include "print.h" #include "init.h" #inc…

Android Studio版本升级那些事

Android Studio版本升级那些事 文章目录 Android Studio版本升级那些事一、前言二、Android Studio版本相关知识1、Android13 签名应用无法在Android Studio 编译运行解决&#xff08;1&#xff09;无法编译运行前的尝试 2、Android Studio 的历史版本介绍4、Android Studio Gr…