3分钟上手ProxyPin抓包分析:从导出到Python可视化全流程

【免费下载链接】network_proxy_flutter 开源免费抓包软件ProxyPin,支持全平台系统,用flutter框架开发 【免费下载链接】network_proxy_flutter 项目地址: https://gitcode.com/GitHub_Trending/ne/network_proxy_flutter

你是否还在为APP接口调试时的参数验证、前端性能优化时的请求耗时分析、后端接口联调时的异常排查而烦恼?本文将带你使用ProxyPin(一款基于Flutter开发的全平台开源抓包工具)完成从数据捕获到Python可视化分析的完整流程,无需复杂配置,零基础也能快速上手。

一、导出抓包数据:3步完成历史记录导出

ProxyPin采用HAR(HTTP Archive)格式存储抓包数据,该格式是Web性能数据的国际标准,可被多种工具解析。历史记录管理核心实现位于lib/storage/histories.dart,通过HistoryStorage类处理数据的持久化与导出。

1.1 启动抓包并生成历史记录

在ProxyPin主界面点击"开始抓包"按钮,工具会自动记录所有HTTP/HTTPS请求。抓包过程中,数据实时写入本地文件系统,默认存储路径由lib/storage/path.dart定义,通常位于应用沙盒的history目录下,文件命名格式为时间戳.txt

1.2 导出HAR格式文件

在"历史记录"页面选择需要分析的会话,点击"导出"按钮即可生成HAR文件。导出功能通过lib/utils/har.dart实现,核心代码如下:

// HAR格式转换实现
static Future<String> writeJson(List<HttpRequest> list, {String title = ''}) async {
  var entries = _entries(list);
  Map har = {};
  title = title.contains("ProxyPin") ? title : "[ProxyPin]$title";
  har["log"] = {
    "version": "1.2",
    "creator": {"name": "ProxyPin", "version": AppConfiguration.version},
    "pages": [/* 页面信息 */],
    "entries": entries, // 请求详细数据
  };
  return jsonEncode(har);
}

1.3 确认导出文件完整性

导出的HAR文件包含请求时间、方法、URL、 headers、响应状态等完整信息。可通过文件大小初步判断数据完整性,单个请求约占用1-2KB空间,1000条请求的文件大小通常在1-2MB左右。文件格式验证可使用工具类中的test/requests_test.py进行基础校验。

二、Python解析脚本:从HAR文件到DataFrame

2.1 解析HAR文件核心代码

以下Python脚本可将HAR文件转换为Pandas DataFrame,便于后续分析:

import json
import pandas as pd
from datetime import datetime

def har_to_dataframe(har_path):
    with open(har_path, 'r', encoding='utf-8') as f:
        har_data = json.load(f)
    
    entries = har_data['log']['entries']
    data = []
    for entry in entries:
        request = entry['request']
        response = entry['response']
        row = {
            'url': request['url'],
            'method': request['method'],
            'status': response['status'],
            'statusText': response['statusText'],
            'startedDateTime': entry['startedDateTime'],
            'duration': entry['time'],  # 单位:毫秒
            'requestSize': request['bodySize'],
            'responseSize': response['bodySize'],
            'serverIP': entry.get('serverIPAddress', '')
        }
        data.append(row)
    
    df = pd.DataFrame(data)
    # 转换时间格式
    df['startedDateTime'] = pd.to_datetime(df['startedDateTime'])
    return df

# 使用示例
df = har_to_dataframe('proxy_pin_capture.har')
print(f"解析完成,共{len(df)}条请求数据")

2.2 数据清洗与预处理

实际分析中可能需要处理异常值,例如过滤静态资源请求、处理超时记录等:

# 过滤非业务接口(保留API请求)
api_df = df[df['url'].str.contains(r'api|rest|v\d+')]

# 移除耗时为0的异常数据
api_df = api_df[api_df['duration'] > 0]

# 添加时间戳列(便于按时间段分析)
api_df['hour'] = api_df['startedDateTime'].dt.hour

三、可视化分析:3种核心图表展示

3.1 请求耗时分布柱状图

分析接口响应时间分布,识别性能瓶颈:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(12, 6))
sns.histplot(data=api_df, x='duration', bins=30, kde=True)
plt.title('API请求耗时分布')
plt.xlabel('耗时(ms)')
plt.ylabel('请求数量')
plt.axvline(x=500, color='r', linestyle='--', label='500ms阈值')
plt.legend()
plt.savefig('duration_distribution.png', dpi=300)

该图表可直观展示有多少请求符合"200ms内响应"的最佳实践标准,帮助评估系统性能是否达标。

3.2 接口访问频次热力图

按小时统计接口访问量,识别流量高峰时段:

# 按小时和接口分组统计请求数
pivot_df = api_df.groupby(['hour', 'url'])['method'].count().unstack()

plt.figure(figsize=(15, 8))
sns.heatmap(pivot_df, cmap='YlGnBu', annot=True, fmt='d')
plt.title('接口访问频次热力图(小时/接口)')
plt.xlabel('接口URL')
plt.ylabel('小时')
plt.savefig('api_heatmap.png', dpi=300)

3.3 状态码分布饼图

分析异常请求比例,快速定位服务稳定性问题:

status_counts = api_df['status'].value_counts()

plt.figure(figsize=(8, 8))
plt.pie(status_counts, labels=status_counts.index, autopct='%1.1f%%', startangle=90)
plt.title('API响应状态码分布')
plt.savefig('status_pie.png', dpi=300)

四、进阶应用:自动化分析脚本集成

可将上述流程封装为自动化脚本,结合定时任务实现持续监控。例如通过test/requests_test.py的HTTP请求能力,定期验证关键接口性能:

# 集成requests库实现接口健康检查
import requests

def check_critical_api(url, timeout=1):
    try:
        response = requests.get(url, timeout=timeout)
        return {
            'status': 'success',
            'status_code': response.status_code,
            'response_time': response.elapsed.total_seconds() * 1000
        }
    except Exception as e:
        return {
            'status': 'error',
            'message': str(e)
        }

# 监控支付接口
payment_check = check_critical_api('https://api.example.com/pay')
print(f"支付接口监控结果: {payment_check}")

五、总结与扩展

通过ProxyPin的抓包能力结合Python数据分析,我们可以快速实现:

  • 前端性能优化:识别慢接口与冗余请求
  • 后端接口调试:验证参数传递与响应格式
  • 测试环境监控:自动化检测接口可用性

完整项目代码可从仓库获取,更多高级功能如SSL证书配置(assets/certs/)、WebSocket抓包(lib/network/http/websocket.dart)等可参考官方文档README.md。建议配合工具类模块lib/utils/开发自定义分析功能,满足特定业务需求。

【免费下载链接】network_proxy_flutter 开源免费抓包软件ProxyPin,支持全平台系统,用flutter框架开发 【免费下载链接】network_proxy_flutter 项目地址: https://gitcode.com/GitHub_Trending/ne/network_proxy_flutter

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐