将参数添加到VBA HTTP Post请求

问题描述 投票:0回答:1

让我在帖子前言,指出我很擅长利用VBA的这一方面。

我有兴趣从Web服务请求令牌,这需要我使用我亲自授权的代码发出HTTP“POST”请求。我需要在我的请求中包含此代码以及其他参数,但我很难成功地这样做。我在网上找到的任何细节都用Java格式化他们的请求如下(所有ID都伪造):

POST /services/oauth2/token HTTP/1.1
Host: "YourURL.com" 
grant_type=authorization_code&code=aPrxsmIEeqM9PiQroGEWx1UiMQd95_5JUZ
VEhsOFhS8EVvbfYBBJli2W5fn3zbo.8hojaNW_1g%3D%3D&client_id=3MVG9lKcPoNI
NVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCs
cA9GE&client_secret=1955279925675241571&
redirect_uri=https%3A%2F%2Fwww.mysite.com%2Fcode_callback.jsp

制作这样的请求一直是个人的真正斗争。以下是我的代码的相关组件:

Dim request As WinHttp.WinHttpRequest
Dim
    client_id, 
    redirect_uri,
    grant_type,
    client_secret,
    authcode,
    result,
    token_url, 
As String

Sub testmod()

Set request = New WinHttp.WinHttpRequest
client_id = "MyClientID"
client_secret = "MyClientSecret"
grant_type = "authorization_code"
redirect_uri = "MyRedirectURI"
authcode = "MyAuthorizationCode"
token_url = "MyTokenURL" <--- No specified query string appended

With request
    .Open method:="POST", Url:=token_url
    ''''Including POST Params with Send method''''
    .Send ("{""code"":" & authcode & 
    ",""grant_type"":authorization_code,""client_id"":" & client_id & 
    ",""client_secret"":" & client_secret & ",""redirect_uri"":" & 
    redirect_uri & "}")
    ''''This returns error code 400 denoting a bad request''''
    Debug.Print .StatusText
end with

结束子

有关为什么这些参数导致此请求失败的任何想法?非常感谢任何见解!

excel vba excel-vba
1个回答
0
投票

请求的正文可能需要具有以下结构:

Dim Payload as string

Payload =  "grant_type=" & "authorization_code" & _
"&code=" & "BLAHBLAHBLAH" & _
"&client_id=" & "OFMICEANDMEN" & _
"&client_secret=" & "MELOVEYOULONGTIME" & _
"&redirect_uri=" & "YOUMAYHAVETOUSELOOPBACKADDRESSIFYOUHAVENOREDIRECTURL"

我发送上面的每个垃圾参数值(您将替换为您自己的)都需要在发送请求之前进行URL编码,以便它们在传输过程中不会被更改/损坏。在对URL进行URL编码之前,某些值可能还需要进行base64编码。要知道服务器期望哪些是base64编码的,请参考API文档(肯定看起来'代码'值首先是base64编码,然后是URL编码)。

URL编码可以通过以下方式在较新的Excel版本中完成:Application.Encode(StringToURLEncode),它将返回URL安全字符串。

可以通过创建函数来完成Base64编码。在这个站点搜索base64 encode vba,有很多现成的例子。

根据您要发布到的服务器,您可能需要设置如下标题:

Dim WebClient as WinHttp.WinHttpRequest
Set Webclient = new winhttp.winhttprequest

With webclient
.open "POST", " YOURURL.COM", False
.setrequestHeader "Content-Type", "application/x-www-form-urlencoded"
.send Payload
.waitforresponse
Debug.print .responsetext
End with
© www.soinside.com 2019 - 2024. All rights reserved.