MSXML2.ServerXMLHTTP(或 3.0/6.0 版本)為伺服器端 HTTP 客戶端,支援同步請求、逾時設定、HTTPS、Proxy 等,適合爬蟲、API 串接、內容聚合。
<%
Function GetRemoteContent(url)
Dim http, resText, resBody, charset, bodyStr
Set http = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
' 設定逾時(毫秒):resolve, connect, send, receive
http.setTimeouts 10000, 10000, 10000, 10000
On Error Resume Next
http.Open "GET", url, False
http.Send
On Error GoTo 0
If Err.Number <> 0 Then
GetRemoteContent = "請求失敗: " & Err.Description
Exit Function
End If
If http.Status <> 200 Then
GetRemoteContent = "HTTP 錯誤: " & http.Status & " " & http.StatusText
Exit Function
End If
' 取得原始位元組陣列
resBody = http.ResponseBody
' 從 HTML meta 標籤或 HTTP 標頭偵測編碼
resText = http.ResponseText ' MSXML 嘗試依標頭解碼,可能錯誤
charset = DetectCharset(resText, http.GetResponseHeader("Content-Type"))
' 使用 ADODB.Stream 正確轉碼
GetRemoteContent = BytesToStr(resBody, charset)
End Function
' 偵測編碼:優先 HTTP 標頭,其次 HTML meta charset
Function DetectCharset(html, contentTypeHeader)
Dim re, matches, charset
charset = "utf-8" ' 預設
' 1. 解析 Content-Type 標頭
If contentTypeHeader <> "" Then
Set re = New RegExp
re.IgnoreCase = True
re.Pattern = "charset\s*=\s*([\w-]+)"
Set matches = re.Execute(contentTypeHeader)
If matches.Count > 0 Then charset = matches(0).SubMatches(0)
End If
' 2. 解析 HTML meta
If charset = "utf-8" Then ' 標頭未指定才解析 HTML
re.Pattern = "]+charset\s*=\s*[""']?([\w-]+)"
Set matches = re.Execute(html)
If matches.Count > 0 Then charset = matches(0).SubMatches(0)
End If
DetectCharset = LCase(charset)
End Function
' 位元組陣列轉字串 (ADODB.Stream)
Function BytesToStr(bytes, charset)
Dim stream
Set stream = Server.CreateObject("ADODB.Stream")
stream.Type = 1 ' 二進位
stream.Mode = 3
stream.Open
stream.Write bytes
stream.Position = 0
stream.Type = 2 ' 文字
stream.Charset = charset
BytesToStr = stream.ReadText
stream.Close
Set stream = Nothing
End Function
%>
<%
Dim url, content
url = "https://example.com/page.asp"
content = GetRemoteContent(url)
If Left(content, 6) = "請求失敗" Or Left(content, 5) = "HTTP 錯誤" Then
Response.Write "" & content & ""
Else
Response.Write ""
End If
%>
| 需求 | 實作方式 |
|---|---|
| POST 表單提交 | http.Open "POST", url, False → http.SetRequestHeader "Content-Type", "application/x-www-form-urlencoded" → http.Send "key1=val1&key2=val2" |
| 攜帶 Cookie | http.SetRequestHeader "Cookie", "sessionid=abc123" |
| 設定 User-Agent | http.SetRequestHeader "User-Agent", "Mozilla/5.0 (compatible; MyBot/1.0)" |
| 使用 Proxy | http.SetProxy 2, "proxy.example.com:8080", "", "user", "pass" |
| 忽略 SSL 憑證錯誤 | http.Option(2) = 13056 ' SERVERXMLHTTP_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS |
robots.txt 與 Crawl-delay。setTimeouts 避免長時間阻塞 ASP 執行緒。DetectCharset 正確偵測,必要時強制指定 charset = "gb2312" 或 "big5"。