MSXML2.XMLHTTP发送方法与早期绑定一起使用,后期绑定失败

时间:2008-11-21 13:49:13

标签: http vba msxml xmlhttprequest

以下代码有效。但是,如果我注释掉行Dim objRequest As MSXML2.XMLHTTP并取消注释行Dim objRequest As Object,则会失败并显示错误消息:

  

参数不正确

为什么,以及我可以做些什么(如果有的话)?

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,是的,我知道我必须这样做才能让我的代码在没有引用MSXML类型库的情况下工作。这不是问题所在。无论我是否使用

,使用Dim objRequest As Object时代码都会失败 带引用的

Set objRequest = NEW MSXML2.XMLHTTP

Set objRequest = CreateObject("MSXML2.XMLHTTP")没有参考。

3 个答案:

答案 0 :(得分:15)

出于某种原因,这有效:

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

不是通过字符串连接构建URL编码的strPostData,而是强烈建议使用URL编码功能:

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

VBA中URLEncode()函数的几个选择在这个帖子中:How can I URL encode a string in Excel VBA?

答案 1 :(得分:2)

如果您使用Dim objRequest As Object,则需要编码:
    设置objRequest = CreateObject(“MSXML2.XMLHTTP”)

答案 2 :(得分:0)

我意识到这几乎与Tomalek上面的代码完全相同(所有归功于你!),但这个问题帮助我完全解决了我遇到的问题(Excel提交给PHP服务器,然后处理响应) ......所以如果这对任何其他人有任何帮助:

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