cHttpClient 组件概述
简介
cHttpClient 是一个基于 WinHTTP 的 HTTP 客户端组件,提供完整的 HTTP 请求功能,支持同步/异步请求、链式调用、JSON 处理、Cookie 管理等特性。同时提供 cSSEClient 实现 SSE (Server-Sent Events) 实时消息接收。
特性
| 特性 | 说明 |
|---|---|
| HTTP 方法 | 支持 GET/POST/PUT/DELETE/OPTIONS |
| 数据格式 | JSON、Form-UrlEncoded、Text 自动处理 |
| 同步/异步 | 支持同步和异步请求模式 |
| 链式调用 | 流畅的 API 设计,支持链式操作 |
| Cookie 管理 | 自动解析和设置 Cookies |
| SSL 支持 | 自动忽略 SSL 证书错误 |
| 编码处理 | 支持 UTF-8 编码自动转换 |
| 调试模式 | 提供详细请求/响应调试信息 |
| SSE 支持 | 独立的 SSE 客户端实现实时消息 |
快速开始
HTTP GET 请求
vb
Dim http As New cHttpClient
Dim result As String
' 简单 GET 请求
result = http.SendGet("https://api.example.com/users").ReturnText()
' 带查询参数的 GET 请求
result = http.SendGet("https://api.example.com/users") _
.AddQueryParam("page", "1") _
.AddQueryParam("limit", "10") _
.ReturnText()HTTP POST 请求 (JSON)
vb
Dim http As New cHttpClient
Dim json As cJson
Set json = New cJson
json.AddItem "name", "张三"
json.AddItem "age", 25
Set http.RequestDataJson = json
Dim response As cJson
Set response = http.SendPost("https://api.example.com/users").ReturnJson()HTTP POST 请求 (Form)
vb
Dim http As New cHttpClient
http.RequestDataForm("username") = "admin"
http.RequestDataForm("password") = "123456"
Dim result As String
result = http.SendPost("https://api.example.com/login").ReturnText()异步请求
vb
Private WithEvents HttpClient As cHttpClient
Private Sub StartAsyncRequest()
Set HttpClient = New cHttpClient
HttpClient.Async(True).SendGet("https://api.example.com/data")
End Sub
Private Sub HttpClient_OnResponseFinished()
Debug.Print "响应完成: " & HttpClient.ReturnText()
End Sub
Private Sub HttpClient_OnError(ByVal ErrorNumber As Long, ByVal ErrorDescription As String)
Debug.Print "错误: " & ErrorDescription
End SubSSE (Server-Sent Events)
vb
Private WithEvents SSE As cSSEClient
Private Sub InitializeSSE()
Set SSE = New cSSEClient
SSE.AutoReconnect = True
SSE.ReconnectInterval = 3000 ' 3秒重连间隔
SSE.MaxReconnectAttempts = 10
Call SSE.Connect("https://api.example.com/events")
End Sub
Private Sub SSE_OnOpen()
Debug.Print "SSE 连接已建立"
End Sub
Private Sub SSE_OnMessage(EventName As String, Data As String, Id As String)
Debug.Print "收到消息: " & EventName & " = " & Data
End Sub
Private Sub SSE_OnError(Description As String, ErrorNumber As Long)
Debug.Print "SSE 错误: " & Description
End Sub
Private Sub SSE_OnClose()
Debug.Print "SSE 连接已关闭"
End Sub引用组件
Microsoft WinHTTP Services, version 5.1Microsoft Scripting RuntimecJson.clscTimer.cls(SSE 需要)
文件结构
| 文件 | 说明 |
|---|---|
cHttpClient.cls | HTTP 客户端主类 |
cSSEClient.cls | SSE 客户端实现 |
mSSEDemo.bas | SSE 使用示例 |
SSE_Client_使用文档.md | SSE 详细使用文档 |
最后更新: 2026-05-17