weskpga
weskpga

Reputation: 2087

Sending values as parameters in HTTP GET using VBA request

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

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?

Upvotes: 0

Views: 6144

Answers (2)

m  e
m e

Reputation: 291

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:

    HTTPReq.Open "GET", TargetURL, False

replaced by:

    HTTPReq.Open "POST", TargetURL, False

Upvotes: 1

Rabindranath Andujar
Rabindranath Andujar

Reputation: 61

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 = "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.

Hope this helps!

Upvotes: 2

Related Questions