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

前端 未结 3 1380
悲哀的现实
悲哀的现实 2020-12-16 02:41

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

相关标签:
3条回答
  • 2020-12-16 03:04

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

    0 讨论(0)
  • 2020-12-16 03:08

    I realise this is nearly identical to the code from Tomalek above (all credit due to you!), but this question helped me towards a full solution to a problem I had (Excel submitting to PHP server, then dealing with response)...so in case this is of any help to anyone else:

    Sub Button1_Click2()
    
    Dim objXMLSendDoc As Object
    Set objXMLSendDoc = New MSXML2.DOMDocument
    objXMLSendDoc.async = False
    Dim myxml As String
    myxml = "<?xml version='1.0'?><Request>Do Something</Request>"
    If Not objXMLSendDoc.LoadXML(myxml) Then
        Err.Raise objXMLSendDoc.parseError.ErrorCode, , objXMLSendDoc.parseError.reason
    End If
    
    Dim objRequest As MSXML2.XMLHTTP
    Set objRequest = New MSXML2.XMLHTTP
    With objRequest
        .Open "POST", "http://localhost/SISADraftCalcs/Test2.php", False
        .setRequestHeader "Content-Type", "application/xml;charset=UTF-16"
        .setRequestHeader "Cache-Control", "no-cache"
        .send objXMLSendDoc
    End With
    
    Dim objXMLDoc As MSXML2.DOMDocument
    Set objXMLDoc = objRequest.responseXML
    If objXMLDoc.XML = "" Then
        objXMLDoc.LoadXML objRequest.responseText
        If objXMLDoc.parseError.ErrorCode <> 0 Then
            MsgBox objXMLDoc.parseError.reason
        End If
    End If
    
    Dim rootNode As IXMLDOMElement
    Set rootNode = objXMLDoc.DocumentElement
    
    MsgBox rootNode.SelectNodes("text").Item(0).text
    
    End Sub
    
    0 讨论(0)
  • 2020-12-16 03:11

    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?

    0 讨论(0)
提交回复
热议问题