如何使用Excel VBA创建http post调用?

如何使用Excel VBA创建http post调用?,vba,excel,post,winhttp,winhttprequest,Vba,Excel,Post,Winhttp,Winhttprequest,我可以通过调用以下代码轻松完成GET: Dim theURL As String, theRequest As Object theURL = "http://localhost/myapp/encrypt.jsp?str=" & _ encodeStr(range("I10").Value) & "&user=myUser&pass=myPass" Set theRequest = CreateObject("WinHttp.WinHttpRequest

我可以通过调用以下代码轻松完成GET:

Dim theURL As String, theRequest As Object
theURL = "http://localhost/myapp/encrypt.jsp?str=" & _
    encodeStr(range("I10").Value) & "&user=myUser&pass=myPass"
Set theRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
theRequest.Open "GET", theURL 
theRequest.Send
MsgBox theRequest.ResponseText
然而,我在一个帖子上遇到了更多的麻烦。我尝试模拟的表单的html是:

<form method="post" enctype="multipart/form-data" action="managefile?operation=upload">
  <table>
    <tr>
        <h3 align="center">Upload File</h3>
    </tr>
    <tr>
        <td>File:</td>
        <td><input type="file" size="80" name="fname"></td>
        <td><input type="Submit" value="Upload"></td>
    </tr>
  </table>
</form>
从中我得到一个错误,表示API期望

。。。
它正在得到:

-----------------13850284693..(continues)..<MyXML><Node1>ff</Node1></MyXML>.
--------------13850284693..(续)…ff。
这让我相信它可以很好地登录,但没有正确地完成帖子

我试着做同样的事情,只是发送XML,但这也不起作用。这对我来说没有意义,因为API不知道将XML与哪个参数关联

我尝试的最后一件事是运行一个简单的get,它让用户登录并返回cookie,然后将其返回。这似乎做了和上面一样的事情,仍然有一个帖子的问题

下面是我尝试设置cookie的步骤。它的工作方式似乎与我传递参数时的工作方式相同——看起来登录可以工作,但无法正确执行post(特别是我尝试发送的xml):

Dim逻辑请求,最简单的请求
设置loginRequest=CreateObject(“WinHttp.WinHttpRequest.5.1”)
登录请求。打开“GET”,“localhost/myapp/login?user=myUser&pass=myPass”
登录请求。发送
设置PostRequest=CreateObject(“WinHttp.WinHttpRequest.5.1”)
打开“POST”,则为False
postrequest.setRequestHeader“Cookie”,loginRequest.getResponseHeader(“setcookie”)
……等等


其中的字符串与我可以毫无问题地上传到表单的文件内容相同


有什么想法吗?

该网站使用基于cookie的登录。因此,您需要使用GET登录,获取返回的cookie,然后将相同的cookie包含在POST请求的标题中。

感谢Tom的帮助。我尝试了这个方法,但似乎不起作用。我尝试了如下代码:Dim theLoginRequest,thePostRequest Set theLoginRequest=CreateObject(“WinHttp.WinHttpRequest.5.1”)登录请求。打开“GET”,登录请求。发送设置PostRequest=CreateObject(“WinHttp.WinHttpRequest.5.1”)的PostRequest。打开“POST”,“False”的PostRequest.setRequestHeader“Cookie”,登录请求。getResponseHeader(“Set Cookie”)等。结果=类似于将登录参数传递到url.Wow-评论中没有发布代码,好的,我会将其添加到我的主帖子中以便于阅读。
theURL = "http://localhost/myapp/managefile?operation=upload&user=myUser&pass=myPass"
<MyXML>...</MyXML>
-----------------13850284693..(continues)..<MyXML><Node1>ff</Node1></MyXML>.
Dim theLoginRequest, thePostRequest
Set theLoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
theLoginRequest.Open "GET", "localhost/myapp/login?user=myUser&pass=myPass"
theLoginRequest.Send
Set thePostRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
thePostRequest.Open "POST, "<post request>", False
thePostRequest.setRequestHeader "Cookie", theLoginRequest.getResponseHeader("Set-Cookie")