在 VBScript 中發送 HTTP 請求並處理 GZIP 壓縮響應是常見痛點。不同 COM 組件對 GZIP 支持差異巨大。本文實測對比 Msxml2.XMLHTTP、Msxml2.ServerXMLHTTP、WinHttp.WinHttpRequest.5.1 三大組件,並提供 Chilkat.Gzip 第三方組件解壓方案。
| 組件 | 自動解壓 GZIP | 備註 |
|---|---|---|
| Msxml2.XMLHTTP | ✅ 支持 | 客戶端首選,自動處理 Accept-Encoding 與解壓 |
| Msxml2.ServerXMLHTTP | ❌ 返回亂碼 | 服務端組件,不自動解壓 |
| WinHttp.WinHttpRequest.5.1 | ❌ 返回亂碼 | 功能強但需手動解壓 |
' By Demon
Dim http
Set http = CreateObject("Msxml2.XMLHTTP")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
WScript.Echo http.responseText ' 正常輸出 HTML
Dim http
Set http = CreateObject("Msxml2.ServerXMLHTTP")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
WScript.Echo http.responseText ' 輸出亂碼(壓縮二進制)
Dim http
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
WScript.Echo http.responseText ' 輸出亂碼
當必須使用 ServerXMLHTTP 或 WinHttp 時(如需發送 Cookie、偽造 Referer、NTLM 認證等),引入 Chilkat.Gzip 解壓響應體。
Dim Gzip, http
Set Gzip = CreateObject("Chilkat.Gzip")
Gzip.UnlockComponent "" ' 免費試用 30 天
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.open "GET", "https://www.baidu.com", False
http.setRequestHeader "Accept-Encoding", "gzip"
http.send
' 關鍵:responseBody 獲取二進制數組,UncompressString 解壓並轉字符串
WScript.Echo Gzip.UncompressString(http.responseBody, "utf-8")
需要高級 HTTP 功能?(Cookie、Referer、認證、代理)
├─ 否 → 直接用 Msxml2.XMLHTTP(最簡單、自動解壓)
└─ 是 → 必須用 ServerXMLHTTP / WinHttp
├─ 能接受第三方組件?→ Chilkat.Gzip 解壓(免費 30 天,後需授權)
└─ 拒絕第三方?→ 純 VBS 實現 GZIP 解壓算法(性能差、代碼複雜)
responseBody(字節數組)而非 responseText(已嘗試解碼的字符串)UncompressString(byteArray, charset) 一步到位:解壓 + 解碼VBS 無原生位運算、無標準庫,實現 DEFLATE 算法極其痛苦(需手寫 Huffman 編碼、LZ77 解碼、CRC32 校驗)。強烈不建議,除非極度受限環境。
結論:優先用 Msxml2.XMLHTTP。若業務強制需高級 HTTP 功能,Chilkat.Gzip 是性價比最高的橋接方案。長期項目建議遷移至 PowerShell、Python 或 .NET 等現代技術棧,原生支持 GZIP、TLS 1.2+、異步等特性。