使用VBA请求在HTTP GET中将值作为参数发送

时间:2022-08-22 17:45:57

So I am trying to send a basic request to a new API I'm testing out with the following script:

所以我正在尝试向我正在使用以下脚本测试的新API发送基本请求:

Sub CalcDemo()
    TargetURL = "https://my-api-url.com"
    Set HTTPReq = CreateObject("WinHttp.WinHttpRequest.5.1")
    HTTPReq.Open "GET", TargetURL, False
    HTTPReq.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"

    postData = "user=myUsername&password=myPassword"
    HTTPReq.send (postData)
    MsgBox (HTTPReq.responseText)

End Sub

But I'm getting the following error message: HTTP Status 401 - user and password should be specified as parameters on the request. I was under the impression that the manner in which postData is being passed above meant they are sent as parameters, but I guess I am wrong. How can I send a string of parameters?

但是我收到以下错误消息:HTTP状态401 - 应该在请求中将用户和密码指定为参数。我的印象是上面传递postData的方式意味着它们作为参数发送,但我想我错了。如何发送一串参数?

2 个解决方案

#1


1  

As one comment has suggested, you are trying to send a post string usin a GET command. If you replace the folowing line, it should work:

正如一条评论建议的那样,您正在尝试使用GET命令发送帖子字符串。如果你替换下面的行,它应该工作:

    HTTPReq.Open "GET", TargetURL, False

replaced by:

    HTTPReq.Open "POST", TargetURL, False

#2


2  

It seems to me that the value of postData is not collecting the values of the variables myUsername or myPassword. you have to create the concatenated data like so:

在我看来,postData的值不是收集变量myUsername或myPassword的值。你必须像这样创建连接数据:

postData = "user=" & myUsername & "&password=" & myPassword

I suppose that myUsername and myPassword are global variables. Otherwise you also need to pass them as arguments to your function.

我想myUsername和myPassword是全局变量。否则,您还需要将它们作为参数传递给您的函数。

Hope this helps!

希望这可以帮助!

#1


1  

As one comment has suggested, you are trying to send a post string usin a GET command. If you replace the folowing line, it should work:

正如一条评论建议的那样,您正在尝试使用GET命令发送帖子字符串。如果你替换下面的行,它应该工作:

    HTTPReq.Open "GET", TargetURL, False

replaced by:

    HTTPReq.Open "POST", TargetURL, False

#2


2  

It seems to me that the value of postData is not collecting the values of the variables myUsername or myPassword. you have to create the concatenated data like so:

在我看来,postData的值不是收集变量myUsername或myPassword的值。你必须像这样创建连接数据:

postData = "user=" & myUsername & "&password=" & myPassword

I suppose that myUsername and myPassword are global variables. Otherwise you also need to pass them as arguments to your function.

我想myUsername和myPassword是全局变量。否则,您还需要将它们作为参数传递给您的函数。

Hope this helps!

希望这可以帮助!