如何使用VBA从Excel向服务器发送HTTP POST请求?

时间:2008-10-01 16:59:14

标签: excel http excel-vba post serverxmlhttp vba

从Excel电子表格执行HTTP POST需要哪些VBA代码?

6 个答案:

答案 0 :(得分:136)

Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send("")

或者,为了更好地控制HTTP请求,您可以使用WinHttp.WinHttpRequest.5.1代替MSXML2.ServerXMLHTTP

答案 1 :(得分:49)

答案 2 :(得分:39)

除了Bill the Lizard的anwser:

大多数后端解析原始发布数据。例如,在PHP中,您将拥有一个数组$ _POST,其中将存储后期数据中的各个变量。在这种情况下,您必须使用额外的标题“Content-type:application / x-www-form-urlencoded”:

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")

否则你必须阅读变量“$ HTTP_RAW_POST_DATA”的原始发布数据。

答案 3 :(得分:5)

您可以通过添加对MSXML的引用来在VBA项目中使用ServerXMLHTTP。

  1. 打开VBA编辑器(通常通过编辑宏)
  2. 转到可用参考列表
  3. 检查Microsoft XML
  4. 单击“确定”。
  5. (来自Referencing MSXML within VBA Projects

    ServerXMLHTTP MSDN documentation包含有关ServerXMLHTTP的所有属性和方法的完整详细信息。

    简而言之,它基本上是这样的:

    1. 调用open方法连接到远程服务器
    2. 致电send发送请求。
    3. 通过responseXMLresponseTextresponseStreamresponseBody
    4. 阅读回复

答案 4 :(得分:0)

我在使用MSXML库然后使用XMLHttpRequest对象之前这样做了。见http://scriptorium.serve-it.nl/view.php?sid=40

答案 5 :(得分:0)

要完成其他用户的回复:

为此,我创建了一个“ WinHttp.WinHttpRequest.5.1” 对象。

使用VBA从Excel发送带有一些数据的发布请求:

Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")

使用VBA从Excel发送带有令牌身份验证的get请求:

Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send