文章摘要
本文介绍了两段VBA代码的功能与实现,重点展示了如何在VBScript中处理HTTP POST请求。第一段代码`BytesToBstr`用于将输入的`body`参数转换为字符串,并设置字符集`Cset`。该函数通过创建ADO的流对象,执行数据写入和读取操作,最终返回字符串结果。 第二段代码`PostHTTPPage`用于发送POST请求至指定URL,并处理返回的HTTP响应。该函数通过创建MSXML2的HTTP对象发送请求,设置请求头(如`CONTENT-TYPE`为`text/plain`),并读取响应数据。通过`BytesToBstr`函数将二进制响应数据转换为字符串格式。代码还处理了HTTP状态码和潜在的错误信息。 两段代码共同展示了如何在VBScript中完成HTTP请求的发送与处理,适用于Web服务开发。
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
‘==================================================function PostHTTPPage(url,data)
dim Http
set Http=server.createobject(“MSXML2.SERVERXMLHTTP.3.0”)
Http.open “POST”,url,false
Http.setRequestHeader “CONTENT-TYPE”, “text/plain”
Http.send(data)
if Http.readystate<>4 then
exit function
End if
PostHTTPPage=bytesToBSTR(Http.responseBody,”utf-8″)
set http=nothing
if err.number<>0 then err.Clear
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
‘==================================================function PostHTTPPage(url,data)
dim Http
set Http=server.createobject(“MSXML2.SERVERXMLHTTP.3.0”)
Http.open “POST”,url,false
Http.setRequestHeader “CONTENT-TYPE”, “text/plain”
Http.send(data)
if Http.readystate<>4 then
exit function
End if
PostHTTPPage=bytesToBSTR(Http.responseBody,”utf-8″)
set http=nothing
if err.number<>0 then err.Clear
End function
© 版权声明
文章版权归作者所有,未经允许请勿转载。