python调用webservice接口(SOAP)

最近工作中需要调用webservice接口,经过一番资料查询后,整理出下面几个测试方法

SOAP UI 查看wsdl文件

image-20240302104949793

两个测试网站:

QQ 在线状态查询接口:http://ws.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl

  • 参数:QQ 号码
  • 返回:Y、N、E(Y 代表在线、N 代表离线、E 代码参数有误!)

天气预报查询接口:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl

可进行测试,选择Request -> run ,可以看到response

image-20240302105059321

用python的requests模拟请求

QQ 在线状态查询接口

import requests
import xml.etree.ElementTree as ET
def test_webservice_qq():
    wsdl_url = "http://ws.webxml.com.cn/webservices/qqOnlineWebService.asmx"
    headers = {'content-type': 'text/xml;charset=UTF-8',
               'User-Agent': 'Apache-HttpClient/4.5.5 (Java/16.0.1)',
               }

    body = """
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://WebXml.com.cn/">
       <soapenv:Header/>
       <soapenv:Body>
          <web:qqCheckOnline>
             <!--Optional:-->
             <web:qqCode>1251865476</web:qqCode>
          </web:qqCheckOnline>
       </soapenv:Body>
    </soapenv:Envelope>
    """

    response = requests.post(wsdl_url, data=body, headers=headers, verify=False)
    print(response.text)

    # 将返回结果转换成Element对象
    root = ET.fromstring(response.text)

    # 定义命名空间
    namespace = {'web': 'http://WebXml.com.cn/'}

    # 找到返回数据的元素
    element = root.find('.//{http://WebXml.com.cn/}qqCheckOnlineResult', namespace)
    print(element)

    if element is None:
        print("No data found")
        return None

    # 提取数据
    data = element.text
    # 打印数据
    print(data)
test_webservice_qq()

天气预报查询接口

def test_weather():
    wsdl_url = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx"
    headers = {'content-type': 'text/xml;charset=UTF-8',
               'User-Agent': 'Apache-HttpClient/4.5.5 (Java/16.0.1)',
               }

    body = """
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://WebXml.com.cn/">
       <soapenv:Header/>
       <soapenv:Body>
          <web:getRegionCountry/>
       </soapenv:Body>
    </soapenv:Envelope>
       """

    response = requests.post(wsdl_url, data=body, headers=headers, verify=False)
    print(response.text)

    # 将返回结果转换成Element对象
    root = ET.fromstring(response.text)

    # 定义命名空间
    namespace = {'web': 'http://WebXml.com.cn/'}
    # 找到返回数据的元素
    elements = root.findall('.//{http://WebXml.com.cn/}string', namespace)

    for ele in elements:
        # 提取数据
        data = ele.text
        # 打印数据
        print(data)


def test_weather2():
    wsdl_url = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx"
    headers = {'content-type': 'text/xml;charset=UTF-8',
               'User-Agent': 'Apache-HttpClient/4.5.5 (Java/16.0.1)',
               }

    body = """
    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://WebXml.com.cn/">
       <soapenv:Header/>
       <soapenv:Body>
          <web:getRegionDataset/>
       </soapenv:Body>
    </soapenv:Envelope>
       """

    response = requests.post(wsdl_url, data=body, headers=headers, verify=False)
    print(response.text)
test_weather()
# test_weather2()

用python的suds-py3模拟请求

pip install suds-py3

from suds import client


def test_qq():
    url = "http://ws.webxml.com.cn/webservices/qqOnlineWebService.asmx?wsdl"
    # 访问url地址返回一个client对象
    web_s = client.Client(url)
    # 准备参数,请求接口
    res = web_s.service.qqCheckOnline(qqCode='121278987')
    # 获取返回的结果:
    print(res)
    print(dir(res))


def test_weather():
    url = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl"
    from suds.xsd.doctor import Import, ImportDoctor
    imp = Import('http://www.w3.org/2001/XMLSchema', location='http://www.w3.org/2001/XMLSchema.xsd')
    imp.filter.add('http://WebXml.com.cn/')
    doctor = ImportDoctor(imp)
    # 访问url地址返回一个client对象
    web_s = client.Client(url, doctor=doctor)
    # 准备参数,请求接口
    res = web_s.service.getRegionCountry()
    # res = web_s.service.getRegionDataset()
    # 获取返回的结果:
    print(res)
    print(res.string)


test_qq()
test_weather()

如何用python搭建webservice服务端、客户端进行测试

目录划分

webservice
	client
		client.py
	server
		app.py
		service.py

使用Python实现服务端

service.py 服务端启动文件

pip install spyne 
from spyne import Application
from spyne.protocol.soap import Soap11
from spyne.server.wsgi import WsgiApplication
from wsgiref.simple_server import make_server
from app import PyWebService

if __name__ == '__main__':
    soap_app = Application([PyWebService], 'PyWebService2',
                           in_protocol=Soap11(validator='lxml'),
                           out_protocol=Soap11())
    wsgi_app = WsgiApplication(soap_app)

    host = "0.0.0.0"
    port = 9567
    server = make_server(host, port, wsgi_app)
    print('WebService Started')
    print('http://' + host + ':' + str(port) + '/PyWebService/?wsdl')
    server.serve_forever()

app.py webservice接口

import json

from spyne import ServiceBase, rpc, Double
from spyne import Integer, Unicode, String


class User(object):
    def __init__(self, age, user_name):
        self.age = age
        self.user_name = user_name
        self.sex = 0

    def get_user_list(self, current_page, page_size):
        print('====>', current_page, page_size)
        l = []
        for i in range(10):
            l.append({'age': self.age, 'sex': self.sex, 'user_name': self.user_name})
        return l


user_mgr = User(18, 'Tom')


class PyWebService(ServiceBase):
    ...

    @rpc(_returns=Unicode)
    def get_version(self):
        """
        获取系统版本
        :return:
        """
        return json.dumps({'version': 1.0})

    @rpc(Integer, Integer, _returns=Unicode)
    def get_user_list(self, current_page, page_size):
        """
        获取用户列表
        :return:
        """
        return json.dumps(user_mgr.get_user_list(current_page, page_size))

使用Python实现客户端

import requests
import json
import xml.etree.ElementTree as ET
from suds.client import Client


def test1():
    wsdl_url = "http://127.0.0.1:9567/PyWebService/?wsdl"
    client = Client(wsdl_url)  # 创建一个webservice接口对象
    # resp = client.service.get_version()  # 调用这个接口下的get_version方法,无参数
    resp = client.service.get_user_list(1, 10)  # 调用这个接口下的get_version方法,无参数
    print(json.loads(resp))


def test_2():
    wsdl_url = "http://127.0.0.1:9567/PyWebService/"
    headers = {'content-type': 'text/xml;charset=UTF-8',
               'User-Agent': 'Apache-HttpClient/4.5.5 (Java/16.0.1)',
               }
    namespace = 'PyWebService2'
    body = f"""
        <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pyw="{namespace}">
           <soapenv:Header/>
           <soapenv:Body>
              <pyw:get_user_list>
                 <!--Optional:-->
                 <pyw:current_page>1</pyw:current_page>
                 <!--Optional:-->
                 <pyw:page_size>100</pyw:page_size>
              </pyw:get_user_list>
           </soapenv:Body>
        </soapenv:Envelope>
       """

    response = requests.post(wsdl_url, data=body, headers=headers, verify=False)
    print(response.text)
    # 将返回结果转换成Element对象
    root = ET.fromstring(response.text)

    # 定义命名空间
    namespace_ = {'web': f'{namespace}'}

    # 找到返回数据的元素
    element = root.find('.//{%s}get_user_listResult' % namespace, namespace_)

    if element is None:
        print("No data found")
        return None

    # 提取数据
    data = element.text
    # 打印数据
    print("=================================================================")
    print(data)


# test1()
test_2()

参考链接:

https://www.jianshu.com/p/881c6f5301d6

https://www.jianshu.com/p/30d2ea3f3772

https://blog.csdn.net/qq_33196814/article/details/122303882

posted @ 2024-03-02 10:57  hanfe1  阅读(2104)  评论(0编辑  收藏  举报