由于工作需要,需要vb提交xml数据到服务器上,所以,需要找到一个好的方法。
之前有代码使用了MSXML2.XMLHTTP对象进行xml数据取得,而且链接是https形式的,于是就参照代码提交,写了下面这么一个函数,来进行操作
1 Private Function CallAPI(url1 As String,filePath String) 2 'load file 3 Dim document As MSXML2.DOMDocument 4 Set document = CreateObject("MSXML2.DOMDocument") 5 document.Load filePath load xml file 6 send data to server 7 Dim xmlHttp As MSXML2.XMLHTTP 8 Set xmlHttp = MSXML2.XMLHTTP 9 xmlHttp.Open POST",url1,False post method to 10 xmlHttp.setRequestHeader Content-Typeapplication/xml" xml type of http request xml,not text/xml 11 xmlHttp.send (document.xml) 12 clear 13 Nothing 14 15 End Function
但是,提交总是失败,在下面的这句代码就被中断,一直找不到原因。
1 xmlHttp.send (document.xml)
突然想到http协议和https协议是不同的,可能在提交数据时有差异,猜测MSXML2.XMLHTTP对象应该不支持https,经过寻找找到另一个对象WinHttp.WinHttpRequest,于是有了下面的代码
5 document.Load filePath
6
Dim xmlHttps As WinHttp.WinHttpRequest
Set xmlHttps = WinHttp.WinHttpRequest.5.1 9 xmlHttps.Open False
10 xmlHttps.setRequestHeader "
11
12 xmlHttps.send document.xml
13
14 DoEvents
15
16 执行了上面的代码之后程序正常结束,但是远端的服务器中的数据没有变化,查看了xmlHttps.status之后发现,提示没有权限,嗯,服务器那边需要用户名和密码验证的,这边没有设置登录用户名和密码,于是加了一句
11 xmlHttps.SetCredentials 用户名 密码",HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
12
13 xmlHttps.send document.xml
14
15 DoEvents
16
17 执行了代码之后发现,xml对象的数据被正常提交。
总结:
1.MSXML2.XMLHTTP对象不能提交https数据到服务器上
2.WinHttp.WinHttpRequest对象需要显式的设置用户名和密码,在MSXML2.XMLHTTP对象使用的过程中,没有登录的话,会弹出用户名和密码输入框,而WinHttp.WinHttpRequest对象没有,直接提交数据后,提示没有权限
3. 提交xml对象时,设置的请求头部应该是"Content-Type","application/xml"而不是"Content-Type","text/xml"
其它对象也可以达到https提交的效果:
1 ...
2 Dim serverxml As MSXML2.ServerXMLHTTP
3 Set serverxml = MSXML2.ServerXMLHTTP4 serverxml.Open False,0); font-family:'Courier New'!important; line-height:1.5!important">用户名5 serverxml.setRequestHeader 6 serverxml.send document.xml
7 ...
注:WinHttp.WinHttpRequest对象需要添加Microsoft WinHTTP Services,version 5.1组件的引用
MSXML2.XMLHTTP和MSXML2.ServerXMLHTTP需要添加Microsoft MsXml组件的引用