Python调用web service

来源:互联网 发布:machinarium for mac 编辑:程序博客网 时间:2024/05/22 14:44

使用Python下的httplib模块来进行远程service的调用:

基本步奏

1、获取到远程主机的连接

webservice = httplib.HTTP("www.webxml.com.cn")

2、设置请求方式

webservice.putrequest("POST", "/WebServices/WeatherWebService.asmx")


3、设置http请求头信息

webservice.putheader("Host", "www.webxml.com.cn")

webservice.putheader("User-Agent", "Python Post")


webservice.putheader("Content-type", "text/xml; charset=utf-8")


webservice.putheader("Content-length", "%d" % len(SoapMessage))


用来标记这是一个SOAP请求,设置SOAP请求地址,为Host/请求的webservice方法webservice.putheader("SOAPAction",SOAP)


webservice.endheaders()


3、发送请求

webservice.send(SoapMessage)

4、获取响应信息

statuscode, statusmessage, header = webservice.getreply()


5、获取响应结果

reshtml=webservice.getfile().read()

附代码:

# -*- coding: utf-8 -*-  import urllib2  import os  class webService():      def SendRtx(self,Host)  SOAP="\""+Host+"/<span style="font-family: Arial, Helvetica, sans-serif;">getSupportCity\""</span>  SoapMessage=\"""<?xml version="1.0" encoding="utf-8"?>  <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">      <soap:Body>          <getSupportCity xmlns="http://WebXml.com.cn/">              <byProvinceName>广东</byProvinceName>          </getSupportCity>      </soap:Body>  </soap:Envelope>  </span>  """try:      start=time.clock()      webservice = httplib.HTTP(Host)      webservice.putrequest("POST", "<span style="font-family: Arial, Helvetica, sans-serif;">/WebServices/WeatherWebService.asmx</span>")      webservice.putheader("Host", Host)      webservice.putheader("User-Agent", "Python Post")      #webservice.putheader("Content-type", "application/soap+xml; charset=utf-8")      webservice.putheader("Content-type", "text/xml; charset=utf-8")      webservice.putheader("Content-length", "%d" % len(SoapMessage))      webservice.putheader("SOAPAction",SOAP)      webservice.endheaders()      webservice.send(SoapMessage)      statuscode, statusmessage, header = webservice.getreply()      reshtml=webservice.getfile().read()      print statuscode    print trshtml      except Exception as e:          error="Exception:%s" % eprint error     return message  if __name__=="__main__":      Host=sys.argv[1]                                              web=webService()      message=web.SendRtx(Host)  







0 0
原创粉丝点击