当前位置: 首页 > article >正文

Android okhttp 网络链接各阶段监控

步骤 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.Proxy

class LoggingEventListener : EventListener() {
    private var mCallStartTime: Long? = null
    private var mCallEndTime: Long? = null
    private var mDnsStartTime: Long? = null
    private var mDnsEndTime: Long? = null
    private var mConnectStartTime: Long? = null
    private var mSecureConnectStartTime: Long? = null
    private var mSecureConnectEndTime: Long? = null
    private var mConnectEndTime: Long? = null
    private var mRequestHeadersStartTime: Long? = null
    private var mRequestHeadersEndTime: Long? = null
    private var mResponseHeadersStartTime: Long? = null
    private var mResponseHeadersEndTime: Long? = null
    private var mResponseBodyStartTime: Long? = null
    private var mResponseBodyEndTime: Long? = null

    companion 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.IOException

class MainActivity : AppCompatActivity() {

    companion object {
        const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 创建 OkHttpClient 并设置自定义 EventListener
        val 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">

    <TextView
        android: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.kler.cn/a/398799.html

相关文章:

  • 计算机编程中的设计模式及其在简化复杂系统设计中的应用
  • Solana 区块链的技术解析及未来展望 #dapp开发#公链搭建
  • PCB+SMT线上报价系统+PCB生产ERP系统自动化拼板模块升级
  • 【目标检测】【Ultralytics-YOLO系列】Windows11下YOLOV5人脸目标检测
  • 时间序列分析——移动平均法、指数平滑法、逐步回归法、趋势外推法等(基于Python实现)
  • Bugku CTF_Web——No one knows regex better than me
  • c++入门基础(三)
  • ElasticSearch-全文检索(一)基本介绍
  • Golang语言系列-哈希表
  • MySQL基础(初阶+进阶)(详解)
  • Java Function 的妙用:化繁为简的魔法师!
  • 条件竞争(ctf.show web87)
  • 图形最高分
  • Unreal engine5实现类似鬼泣5维吉尔二段跳
  • 基于YOLOv8深度学习的不良坐姿监测与语音提醒系统(PyQt5界面+数据集+训练代码)
  • Spring Boot【一】
  • 【保姆级】Mac上IDEA卡顿优化
  • STM32低功耗设计NFC与无线距离感应智能钥匙扣
  • 《探索Zynq MPSoC》学习笔记(三)
  • Leetcode160.相交链表
  • PyTorch——从入门到精通:PyTorch基础知识(张量)【PyTorch系统学习】
  • React Native 全栈开发实战班 - 图片加载与优化
  • MCU的时钟体系
  • spring-data-elasticsearch 3.2.4 实现桶bucket排序去重,实现指定字段的聚合搜索
  • Adobe Illustrator(Ai)修图软件入门操作参考,收集查过的各个细节用法
  • 第十六届蓝桥杯模拟赛(第一期)-c++/c