Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

http - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...