启蒙链接
Python | How do I make a SOAP request?
Note: 所例举的 url 因项目保密性全部隐去,请以您的实际 url 测试即可。
步骤总结
-
准备好用 soap 协议的 url
url = "http://XXX.com/XXX/XXXXXXXXXX.asmx"
-
准备好协议声明的请求消息头,注意请求消息头的 keys 大小写要求。知道了服务端的要求手打也没问题
# 无视请求消息头对 keys 大小写的格式要求, # 即如下的 headers['Content-Type'] 改成 headers['cOnTent-typE'] 也能变成服务端认可的请求消息头的键值对 # headers = CaseInsensitiveDict() # headers['Content-Type'] = 'application/soap+xml' headers = { 'Content-Type': 'application/soap+xml' }
-
准备发送的 data,要传的参数也是在 xml 数据中传递。如下传递的是 Number
Note: 如果看的是接口说明文档,且文档中 requests 的 xml 数据里类似如下
declaration
,删掉它。<?xml version="1.0" encoding="utf-8"?>
data = ''' <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <SNInfo xmlns="http://XXXXXX.com/XXXXXX/"> <Number>001031465233</Number> </SNInfo> </soap12:Body> </soap12:Envelope> '''
-
发送 requests 和打印消息
response = requests.post(url=url, headers=headers, data=data) print(response.text)
-
完整代码
import requests from requests.structures import CaseInsensitiveDict from xml import etree url = "http://XXXXXXXXXX.com/XXX/XXXX.asmx" headers = CaseInsensitiveDict() headers['Content-Type'] = 'application/soap+xml' data = ''' <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <SNInfo xmlns="http://XXXXXXXXXXXX.com/XXXXX/"> <Number>001031465233</Number> </SNInfo> </soap12:Body> </soap12:Envelope> ''' response = requests.post(url=url, headers=headers, data=data) print(response.text)
Webservice 和 Web API 的区别
启蒙链接