8.6.3 基于HTTP的调用
基于HTTP协议的Web Service调用也有两种模式,第一种是强制发送XML数据包模拟SOAP请求格式,另一种需要Web Service自身支持HTTP调用模式。
1. 使用HTTP协议进行SOAP模拟
对于SOAP协议我们前面有所研究,但是并没有说透,对于查询城市编号的这个操作,SOAP的请求格式其实是这个样子的:
POST /WebServices/WeatherWS.asmx HTTP/1.1 <?xml version="1.0" encoding="utf-8"?> |
也就是说我们只需要使用web_custom_request()函数往服务器上的这个地址抛一个XML数据包就行了。新建一个HTTP/HTML协议的脚本,在里面通过web_custom_request()函数发送对应的数据包,代码如下:
web_custom_request("web_custom_request", "URL=http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx", "Method=POST", "TargetFrame=", "Resource=0", "Referer=", "Body=<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">" " <soap12:Body>" " <getSupportCityString xmlns=\"http://WebXml.com.cn/\">" " <theRegionCode>string</theRegionCode>" " </getSupportCityString>" " </soap12:Body>" "</soap12:Envelope>", LAST); |
但是这个数据包直接运行后会得到服务器返回的错误:
Action.c(17): Error -26616: HTTP Status-Code=415 (Unsupported Media Type) for "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx" [MsgId: MERR-26616] |
这个错误的原因是我们发送的数据包没有明确格式类型,服务器在校验格式时出现错误,所以我们需要手动添加一个Header头部分,使用函数web_add_header()添加Content-Type: application/soap+xml; charset=utf-8头信息:
web_add_header("Content-Type","application/soap+xml; charset=utf-8"); |
添加这行代码后再次运行,请求成功发送,返回的内容可以通过web_reg_save_ param_*关联函数解决,将<theRegionCode>string</theRegionCode>中的string替换为上海的UTF-8编码,请求前添加头信息,编写关联函数即可完成该Web Service的调用,完整代码如下:
web_add_header("Content-Type", web_reg_save_param_ex( web_custom_request("web_custom_request", |
检查返回可以看到成功关联到和上海有关的12个区域编号,后续开发略。