使用的WebService地址为http://webservice.webxml.com.cn/WebServices/WeatherWebService.asmx,所使用的服务方法为getWeatherbyCityName,访问上述地址可以看到该服务的说明。
方法getWeatherbyCityName的Http请求报文格式示例如下:
SOAP 1.1
POST /WebServices/WeatherWebService.asmx HTTP/1.1 Host: webservice.webxml.com.cn Content-Type: text/xml; charset=utf-8 Content-Length: length SOAPAction: "http://WebXml.com.cn/getWeatherbyCityName" <?xml version="1.0" encoding="utf-8"?> <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/"> <soap:Body> <getWeatherbyCityName xmlns="http://WebXml.com.cn/"> <theCityName>string</theCityName> </getWeatherbyCityName> </soap:Body> </soap:Envelope>
GET /WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=string HTTP/1.1 Host: webservice.webxml.com.cn
POST /WebServices/WeatherWebService.asmx/getWeatherbyCityName HTTP/1.1 Host: webservice.webxml.com.cn Content-Type: application/x-www-form-urlencoded Content-Length: length theCityName=string
对于以上三种Http请求报文,使用python的httplib库构造起来很方便。
通过Http请求来访问该WebService的代码示例如下:
- import httplib
- import urllib
- *host值通过上面报文即可得到
- host = "webservice.webxml.com.cn"
- *建立连接
- conn = httplib.HTTPConnection(host)
- *SOAP 1.1
- def bySoap():
- *soap报文内容一定要copy原WebService给出的示例,写错非常难debug
- soapMessage ='''<?xml version="1.0" encoding="utf-8"?>
- <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/">
- <soap:Body>
- <getWeatherbyCityName xmlns="http://WebXml.com.cn/">
- <theCityName>beijing</theCityName>
- </getWeatherbyCityName>
- </soap:Body>
- </soap:Envelope>'''
- *Http报文头
- headers = {"Content-Type":"text/xml; charset=utf-8",
- "Content-Length":"%d" % len(soapMessage),
- "SOAPAction":"\"http://WebXml.com.cn/getWeatherbyCityName\""}
- *发送请求
- conn.request("POST", "/WebServices/WeatherWebService.asmx", '', headers)
- *发送Soap报文
- conn.send(soapMessage)
- *获得响应
- r = conn.getresponse()
- print r.read()
- *HTTP GET
- def byHttpGet():
- *发送请求
- conn.request("GET", "/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=beijing")
- *获得响应
- r = conn.getresponse()
- print r.read()
- *HTTP POST
- def byHttpPost():
- *post参数需要urlencode
- params = urllib.urlencode({'theCityName':'beijing'})
- *Http报文头
- headers = {'Content-Type': 'application/x-www-form-urlencoded'}
- *发送请求
- conn.request("POST", "/WebServices/WeatherWebService.asmx/getWeatherbyCityName", params, headers)
- *获得响应
- r = conn.getresponse()
- print r.read()
- def main():
- bySoap()
- byHttpGet()
- byHttpPost()
- *关闭连接
- conn.close()
- if __name__ == '__main__':
- main()