下面的代码有效。但是,如果我注释掉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
科里,是的,我知道我必须这样做才能使我的代码在不引用MSXML类型库的情况下工作。这不是这里的问题。无论我是否使用
Dim objRequest As Object
,代码都会失败带有引用的
Set objRequest = NEW MSXML2.XMLHTTP
,或者没有引用的
Set objRequest = CreateObject("MSXML2.XMLHTTP")
。 最佳答案
由于某些原因,这可行:
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编码功能,而不是通过字符串连接来构建URL编码的
strPostData
:strPostData = "api_id=" & URLEncode(strApiId) & _
"&user=" & URLEncode(strUserName) & _
"&password=" & URLEncode(strPassword)
此线程中有VBA中
URLEncode()
函数的几个选择:How can I URL encode a string in Excel VBA?关于http - MSXML2.XMLHTTP send方法可用于早期绑定(bind),而无法用于后期绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/308826/