用 ASP 抓取遠程頁面時,最關鍵的一步是「編碼還原」。因為 XMLHTTP 返回的是二進制的 responseBody,必須手動轉換為字符串才能正常顯示中文。下面的代碼把 getHTTPPage 與 bytes2BSTR 兩個函數組合起來,實現了完整的抓取與轉碼流程。
<%
function getHTTPPage(url)
on error resume next
dim http
set http = Server.createobject("Microsoft.XMLHTTP")
Http.open "GET", url, false
Http.send()
if Http.readystate <> 4 then
exit function
end if
getHTTPPage = bytes2BSTR(Http.responseBody)
set http = nothing
if err.number <> 0 then err.Clear
end function
Function bytes2BSTR(vIn)
dim strReturn
dim i1, ThisCharCode, NextCharCode
strReturn = ""
For i1 = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn, i1, 1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn, i1+1, 1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i1 = i1 + 1
End If
Next
bytes2BSTR = strReturn
End Function
%>
這段代碼的精髓在於 bytes2BSTR:它逐個讀取二進制字節,判斷是否屬於 ASCII 範圍(小於 &H80)。若是 ASCII 字符就直接轉換;否則說明這是一個雙字節的中文字符,需要把連續兩個字節合併計算,再還原成對應字符。這樣一來,抓取回來的頁面就能正確顯示中文,而不會出現亂碼。