您的位置:首页 > 理论基础 > 计算机网络

ASP模拟POST提交,然后XMLHTTP获取数据总是乱码,请大家帮忙,感谢!

2017-03-06 22:18 405 查看
目前在建的一个项目要求使用外部的一个网站达到切词的目的,由于外部网站的API接口要求必须是POST提交数据,因此只能模拟POST提交,然后再去读取提交后的数据,我用以下的代码,获取回来的中文总是乱码,英文和数字没有问题,请大家帮忙看看,非常感谢!

<%

On error resume next 

Function GetBody(ips) 

Set https = Server.CreateObject("MSXML2.XMLHTTP") 

With https 

.Open "Post", "http://www.ftphp.com/scws/api.php", False

.setRequestHeader "Content-Type","application/x-www-form-urlencoded;charset=utf-8"

.Send "data="&ips&"&respond=xml&charset=utf8&ignore=yes&duality=yes&traditional=no&multi=5"

GetBody = .ResponseBody

End With 

GetBody = BytesToBstr(GetBody,"utf-8")

Set https = Nothing 

End Function

Function BytesToBstr(body,Cset) 

dim objstream

set objstream = Server.CreateObject("adodb.stream")

objstream.Type = 1

objstream.Mode =3

objstream.Open

objstream.Write body

objstream.Position = 0

objstream.Type = 2

objstream.Charset = Cset

BytesToBstr = objstream.ReadText 

objstream.Close

set objstream = nothing

End Function

Response.Write GetBody("我们的李宇春天")

%>

是中文的且没有任何问题,
你发的代码,可以正确请求,并得到内容,且中文可以正常显示. ..



文件保存成UTF-8编码.(保存时可以用计事本另存为,编码选择UTF-8即可)
保存的UTF-8编码的文件,需要 BOM 头(IIS需要BOM头才能确定它是UTF-8编码的文件,我在XP下测试的,如果没有BOM头,则会显示ASP错误,因为IIS把它当成GB2312来解析了,然后那些UTF-8编码的汉字就会导致解析出错).


 

服务器交互时发送的HTTP交互的完整请求(对方返回的内容是UTF-8编码的内容,所以在ASP获取以后不需要转码,如果你需要以GB2312显示的时候才需要转)

POST /scws/api.php HTTP/1.0

Accept: */*

Content-Type: application/x-www-form-urlencoded;charset=utf-8

User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET4.0C; .NET4.0E)

Host: www.ftphp.com

Content-Length: 97

Connection: Keep-Alive

Pragma: no-cache

data=我们的李宇春天&respond=xml&charset=utf8&ignore=yes&duality=yes&traditional=no&multi=5

HTTP/1.1 200 OK

Server: nginx

Date: Mon, 09 Apr 2012 06:12:12 GMT

Content-Type: text/xml; charset=utf-8

Connection: close

Vary: Accept-Encoding

<?xml version="1.0" encoding="utf-8"?>

<scws:respond xmlns:scws="http://www.ftphp.com/scws">

        <status>ok</status>

        <words>

                <word><![CDATA[我们]]></word>

                <off>0</off>

                <len>6</len>

                <idf>4.4200000762939</idf>

                <attr>r</attr>

        </words>

        <words>

                <word><![CDATA[的]]></word>

                <off>6</off>

                <len>3</len>

                <idf>0</idf>

                <attr>uj</attr>

        </words>

        <words>

                <word><![CDATA[李宇春]]></word>

                <off>9</off>

                <len>9</len>

                <idf>9.3599996566772</idf>

                <attr>nr</attr>

        </words>

        <words>

                <word><![CDATA[天]]></word>

                <off>18</off>

                <len>3</len>

                <idf>0</idf>

                <attr>n</attr>

        </words>

</scws:respond>

复制代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: