Python调用web service

使用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" % e
	print error 
    return message  
if __name__=="__main__":  
    Host=sys.argv[1]                                          
    web=webService()  
    message=web.SendRtx(Host)  







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值