提供三個核心 VBScript 函數:中文轉 URL 編碼(Unicode 逃逸)、Unicode 還原為可讀文本、XMLHTTP 取遠程內容並自動解碼。
逐字符檢測,ASCII 碼 > 255 視為雙字節字符,拆解高低位組成 %HIGH%LOW 格式。
' 轉換中文為 Unicode URL 編碼
Function URLEncoding(vstrIn)
Dim i, strReturn, ThisChr, innerCode, Hight8, Low8
strReturn = ""
For i = 1 To Len(vstrIn)
ThisChr = Mid(vstrIn, i, 1)
If Abs(Asc(ThisChr)) < &HFF Then
strReturn = strReturn & ThisChr
Else
innerCode = Asc(ThisChr)
If innerCode < 0 Then innerCode = innerCode + &H10000
Hight8 = (innerCode And &HFF00) \ &HFF
Low8 = innerCode And &HFF
strReturn = strReturn & "%" & Hex(Hight8) & "%" & Hex(Low8)
End If
Next
URLEncoding = strReturn
End Function
處理 responseBody 類型資料,逐雙字節組合 Chr(High*256 + Low) 還原中文。
' 轉換 Unicode 位元組流為正常文本
Function bytes2BSTR(vIn)
Dim i, strReturn, ThisCharCode, nextCharCode
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn, i, 1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
nextCharCode = AscB(MidB(vIn, i + 1, 1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(nextCharCode))
i = i + 1
End If
Next
bytes2BSTR = strReturn
End Function
自動建立 MSXML2.XMLHTTP,同步請求,狀態 200 時自動調用 bytes2BSTR 解碼返回文本。
Function getText(oReq, url)
On Error Resume Next
If oReq Is Nothing Then Set oReq = CreateObject("MSXML2.XMLHTTP")
If Not oReq Is Nothing Then
oReq.open "GET", url, False
oReq.send
If oReq.status = 200 Then
getText = bytes2BSTR(oReq.responseBody)
Else
getText = ""
End If
Else
getText = ""
End If
End Function
HttpUtility.UrlEncode/UrlDecode、Encoding.GetEncoding 更穩健。On Error Resume Next,改用具體錯誤捕獲記錄日誌。<%
Dim oReq, url, encoded, decoded
url = "https://example.com/api?keyword=中文測試"
encoded = URLEncoding("中文測試") ' 輸出 %D6%D0%CE%C4%B2%E2%CA%D4
' 假設遠程返回 Unicode 位元組流
' decoded = getText(oReq, url & "&kw=" & encoded)
Response.Write "編碼結果:" & encoded
%>