在Python中为SOAP请求消息添加头部
我在用Python发送SOAP请求的时候,想要添加一个头部信息。
SOAP中的头部信息是:
> <SOAP-ENV:Header>
> <ns3:userCredentials
> xsi:type="https://4psa.com/HeaderData.xsd/2.0.0">
> <username>admin</username>
> <password>welcome</password>
> </ns3:userCredentials>
> </SOAP-ENV:Header>
我使用了:
from suds.client import Client
from suds.xsd.doctor import ImportDoctor, Import
wsdl = 'https://192.168.1.15//soap2/schema/2.5.0/Report/Report.wsdl'
client = Client(wsdl)
但是我不知道怎么把头部信息加到这段代码里。
请告诉我怎么添加。
我还尝试过:
> >>> from suds.client import Client
> >>> from suds.xsd.doctor import ImportDoctor, Import
> >>> imp = Import('http://schemas.xmlsoap.org/soap/encoding/')
> >>> url = 'https://192.168.1.15//soap2/schema/2.5.0/Report/Report.wsdl'
> >>> client = Client(url)
> >>> userid = 'admin'
> >>> passwd = '12345678@X'
> >>> client.set_options(soapheaders=(userid,passwd))
> >>> print client a get error when run:
>
> >>> client.service.CallCosts(1) Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/client.py",
> line 542, in __call__
> return client.invoke(args, kwargs) File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/client.py",
> line 602, in invoke
> result = self.send(soapenv) File "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/client.py",
> line 637, in send
> reply = transport.send(request) File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/transport/https.py",
> line 64, in send
> return HttpTransport.send(self, request) File
> "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/transport/http.py", line 77, in send
> fp = self.u2open(u2request) File "/usr/local/lib/python2.6/dist-packages/suds-0.4-py2.6.egg/suds/transport/http.py", line 118, in u2open
> return url.open(u2request, timeout=tm) File
> "/usr/lib/python2.6/urllib2.py", line
> 391, in open
> response = self._open(req, data) File "/usr/lib/python2.6/urllib2.py",
> line 409, in _open
> '_open', req) File "/usr/lib/python2.6/urllib2.py", line
> 369, in _call_chain
> result = func(*args) File "/usr/lib/python2.6/urllib2.py", line
> 1169, in https_open
> return self.do_open(httplib.HTTPSConnection,
> req) File
> "/usr/lib/python2.6/urllib2.py", line
> 1136, in do_open
> raise URLError(err) urllib2.URLError: <urlopen error
> [Errno 111] Connection refused>
如果你知道这里有什么问题,请告诉我。
2 个回答
0
suds客户端有很多选项可以用来控制这个库的行为。有些是通用选项,有些是传输选项。虽然这些选项对象是可以使用的,但推荐和支持的设置或取消选项的方式是通过以下几种方法:
- 客户端构造函数
- Client.set_options() 方法
- 传输构造函数。
soapheaders – 用于提供soap头信息。
1
我做了类似这样的事情
def client_with_token(token):
header_ns = ('ns1', "http://4psa.com/HeaderData.xsd/3.5.0")
access_token = Element('accessToken', ns=header_ns).setText(token)
auth_header = Element('userCredentials', ns=header_ns)
auth_header.append(access_token)
client = Client(url)
auth_header = get_auth_header()
client.set_options(soapheaders=auth_header, *args, **kwargs)
return client