MSXML2.XMLHTTP 发送方法适用于早期绑定,后期绑定失败 [英] MSXML2.XMLHTTP send method works with early binding, fails with late binding
问题描述
下面的代码有效.但是,如果我注释掉 Dim objRequest As MSXML2.XMLHTTP
行并取消注释 Dim objRequest As Object
行,它会失败并显示错误消息:
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 :
参数不正确
为什么,我能做些什么(如果有的话)?
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,是的,我知道我必须这样做才能让我的代码在不引用 MSXML 类型库的情况下工作.这不是这里的问题.无论我是否使用
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
使用引用设置 objRequest = NEW MSXML2.XMLHTTP
,或
设置 objRequest = CreateObject("MSXML2.XMLHTTP")
没有引用.
推荐答案
由于某种原因,这行得通:
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
不要通过字符串连接构建 URL 编码的 strPostData
,强烈建议使用 URL 编码函数:
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)
VBA 中 URLEncode()
函数的几个选择在此线程中:如何在 Excel VBA 中对字符串进行 URL 编码?
A couple of choices for a URLEncode()
function in VBA are in this thread: How can I URL encode a string in Excel VBA?
这篇关于MSXML2.XMLHTTP 发送方法适用于早期绑定,后期绑定失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!