Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSXML2.XMLHTTP send method works with early binding, fails with late binding

The code below works. But if I comment out the line Dim objRequest As MSXML2.XMLHTTP and uncomment the line Dim objRequest As Object it fails with the error message :

The parameter is incorrect

Why, and what (if anything) can I do about it?

Public Function GetSessionId(strApiId, strUserName, strPassword) As String

    Dim strPostData As String

    Dim objRequest As MSXML2.XMLHTTP
    'Dim objRequest As Object '

    strPostData = "api_id=" & strApiId & "&user=" & strUserName & "&password=" & strPassword

    Set objRequest = New MSXML2.XMLHTTP
    With objRequest
        .Open "POST", "https://api.clickatell.com/http/auth", False
        .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        .send strPostData
        GetSessionId = .responseText
    End With

End Function

Corey, yes, I know I would have to do that in order for my code to work without a reference to the MSXML type library. That's not the issue here. The code fails when using Dim objRequest As Object regardless of whether I use

Set objRequest = NEW MSXML2.XMLHTTP with the reference, or

Set objRequest = CreateObject("MSXML2.XMLHTTP") without the reference.

like image 942
Brendan Reynolds Avatar asked Nov 21 '08 13:11

Brendan Reynolds


2 Answers

For some reason, this works:

Dim strPostData As String
Dim objRequest As Object

strPostData = "api_id=" & strApiId & "&user=" & strUserName & "&password=" & strPassword

Set objRequest = New MSXML2.XMLHTTP
With objRequest
  .Open "POST", "https://api.clickatell.com/http/auth", False
  .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
  .send (strPostData)
   GetSessionId = .responseText
End With

Instead of building the URL-encoded strPostData via string concatenation, it's strongly advisable to use a URL encoding function:

strPostData = "api_id=" & URLEncode(strApiId) & _
              "&user=" & URLEncode(strUserName) & _
              "&password=" & URLEncode(strPassword)

A couple of choices for a URLEncode() function in VBA are in this thread: How can I URL encode a string in Excel VBA?

like image 165
Tomalak Avatar answered Oct 19 '22 02:10

Tomalak


If you use the Dim objRequest As Object then you would need to code:
Set objRequest = CreateObject("MSXML2.XMLHTTP")

like image 3
Corey Trager Avatar answered Oct 19 '22 03:10

Corey Trager