使用的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>
HTTP GET
GET /WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=string HTTP/1.1 Host: webservice.webxml.com.cn
HTTP POST
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()