ASP调用WebService的两种方法

需积分: 10 11 下载量 57 浏览量 更新于2024-09-17 收藏 22KB DOCX 举报
"ASP链接webservice两种方式" 在ASP(Active Server Pages)中,与Web Service进行交互是通过HTTP协议发送请求并接收响应的过程。这里主要介绍两种常见的方法:HTTP POST和SOAP请求。 1. HTTP POST方法 这种方式通常更为常见,通过创建XMLHttpRequest对象(例如Msxml2.XMLHTTP)来发送POST请求到Web Service的URL。以下是一个简单的示例代码: ```vbscript url = "http://192.168.0.171/nicktest/Service1.asmx/GetCampChal" DataToSend = "sCAMP_ID=11111&sCHAL_CD=21" Set xmlhttp = Server.CreateObject("Msxml2.XMLHTTP") xmlhttp.Open "POST", url, false xmlhttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" ' 可选的HTTP头设置,如HOST和Content-Length ' xmlhttp.setRequestHeader "HOST", "192.168.0.164" ' xmlhttp.setRequestHeader "Content-Length", Len(DataToSend) xmlhttp.Send DataToSend If xmlhttp.Status = 200 Then Response.Write "HTTP状态:" & xmlhttp.Status & "<br>" & xmlhttp.StatusText Response.Write xmlhttp.responseText Else Response.Write "请求失败,状态:" & xmlhttp.Status End If ``` 在.NET Framework 1.1版本中,如果仅支持POST请求的Web服务应用可能会遇到问题,因为它默认不启用HTTP GET。如果遇到`500 InternalServerError`错误,可能是因为缺少对GET方法的支持。在这种情况下,需要在Web Service的`web.config`文件中添加以下配置,允许HTTP GET和POST: ```xml <webServices> <protocols> <add name="HttpGet"/> <add name="HttpPost"/> </protocols> </webServices> ``` 2. SOAP请求方法 当不能修改Web Service,或者需要发送更复杂的XML数据时,可以使用SOAP(Simple Object Access Protocol)协议。SOAP是一种基于XML的协议,用于在Web上交换结构化和类型化的信息。下面是一个ASP发送SOAP请求的例子: ```vbscript Dim strXml, strResponse strXml = "<?xml version='1.0' encoding='utf-8'?>" strXml = strXml & "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" strXml = strXml & "<soap:Body>" strXml = strXml & "<YourMethod xmlns='YourNamespace'>" ' 添加方法参数,例如: strXml = strXml & "<param1>value1</param1>" strXml = strXml & "<param2>value2</param2>" strXml = strXml & "</YourMethod>" strXml = strXml & "</soap:Body>" strXml = strXml & "</soap:Envelope>" Set xmlhttp = Server.CreateObject("Msxml2.XMLHTTP") xmlhttp.Open "POST", "http://yourwebservice.com/service.asmx", false xmlhttp.setRequestHeader "Content-Type", "text/xml; charset=utf-8" xmlhttp.setRequestHeader "SOAPAction", "http://yourwebservice.com/YourMethod" xmlhttp.Send strXml If xmlhttp.Status = 200 Then strResponse = xmlhttp.responseText ' 处理响应 Else Response.Write "请求失败,状态:" & xmlhttp.Status End If ``` 在这个例子中,`YourMethod`是你需要调用的Web服务方法,`YourNamespace`是该方法所在的命名空间,`param1`和`param2`是方法所需的参数。请根据实际的Web服务接口替换这些占位符。 这两种方法提供了ASP连接和调用Web Service的基本途径。HTTP POST适用于简单数据传输,而SOAP请求则适用于需要更复杂交互的情况。选择哪种方法取决于你的具体需求和Web Service的兼容性。