Python 用 requests 请求 SOAP 协议的服务

启蒙链接

Python | How do I make a SOAP request?

Note: 所例举的 url 因项目保密性全部隐去,请以您的实际 url 测试即可。

步骤总结

  1. 准备好用 soap 协议的 url

    url = "http://XXX.com/XXX/XXXXXXXXXX.asmx"
  2. 准备好协议声明的请求消息头,注意请求消息头的 keys 大小写要求。知道了服务端的要求手打也没问题

    # 无视请求消息头对 keys 大小写的格式要求,
    # 即如下的 headers['Content-Type'] 改成 headers['cOnTent-typE'] 也能变成服务端认可的请求消息头的键值对
    # headers = CaseInsensitiveDict()
    # headers['Content-Type'] = 'application/soap+xml'
    
    headers = {
        'Content-Type': 'application/soap+xml'
    }

  3. 准备发送的 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>
    '''
  4. 发送 requests 和打印消息

    response = requests.post(url=url, headers=headers, data=data)
    print(response.text)
  5. 完整代码

    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 的区别

启蒙链接

  WebService与WebApi的区别

  • 23
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值