为什么asp中用xmlHttp抓取到的页面局部有乱码?
Function xmlHttp(sUrl, sCharSet)
On Error Resume Next
Dim xml: set xml = Server.CreateObject("Microsoft.XMLHTTP")
xml.Open "GET", sUrl, False
xml.setRequestHeader "Content-Type", "text/html;charset=" & sCharSet
xml.Send()
If Err.Number <> 0 Then
xmlHttp = ""
Exit Function
End If
If xml.readyState = 4 Then
xmlHttp = BytesToBstr(xml.responseBody, sCharSet)
End If
End Function
Function BytesToBstr(cnvUni, sCharSet)
On Error Resume Next
Dim objStream: set objStream = Server.CreateObject("adodb.stream")
With objStream
.Type = 1
.Mode = 3
.Open
.Write cnvUni
.Position = 0
.Type = 2
.Charset = sCharSet
BytesToBstr = .ReadText
.Close
End With
End Function
url="http://proxy.ncuhome.cn/surf.aspx"
strContent=xmlHttp(url, "gb2312")
response.write strContent
结果显示的大部分是正确的,没有乱码,但是少部分出现乱码(出现乱码的情况见下边的图片)
关键是大多数的中文字都是没问题的啊,只有少部分有问题
我把GB2312改为UTF-8还是不行的
高手帮帮我,我是菜鸟,太感谢了
[解决办法]
用这个函数转换下即可
'S=http.responseBody
function getGBKTEXT(S)
DIM text;
SET adoS=SERVER.CREATEOBJECT("ADODB.Stream")
adoS.Charset="gb2312"
adoS.Type=1 //设置为二进制
adoS.mode=3 //设置可读写
adoS.open
var txt=S
adoS.Write(txt) //用二进制写
adoS.Position=0 //一定要先归0
adoS.Type=2 //才可以设置为文本方式
getGBKTEXT=adoS.ReadText
END FUNCTION
[解决办法]
<%
'取服务器数据
Public Function GetData(ByVal strUrl, ByVal CharSet)
Dim xmlHttp
Set xmlHttp = Server.CreateObject("MSXML2.serverXMLHTTP")
xmlHttp.Open "GET", strUrl, False
xmlHttp.Send
If xmlHttp.readyState <> 4 Then
GetData = "错误: 服务器无响应。"
ElseIf xmlHttp.Status = 200 Then
GetData = Bytes2Bstr__(xmlHttp.responseBody, CharSet)
Else
GetData = "错误:" & xmlHttp.Status & " " & xmlHttp.StatusText
End If
Set xmlHttp = Nothing
End Function
'编码转换
Private Function Bytes2Bstr__(ByVal s, ByVal CharSet)
dim oStrm
set oStrm = Server.CreateObject("Adodb.Stream")
With oStrm
.Type = 1
.Mode = 3
.Open
.Write s
.Position = 0
.Type = 2
.Charset = CharSet
Bytes2Bstr__ = .ReadText
.Close
End With
set oStrm = nothing
End Function
Dim htmlCode
htmlCode = GetData("http://proxy.ncuhome.cn/surf.aspx", "utf-8")
Response.Write htmlCode
%>