什么是SOAP?
SOAP 是一种简单的基于 XML 的协议,它使应用程序通过 HTTP 来交换信息。
或者更简单地说:SOAP 是用于访问网络服务的协议。
一、目标
利用QtSoap访问WebService
环境:
QT5.12.3
Windows10
二、下载QtSoap源码
链接:https://pan.baidu.com/s/1UvsfwSF_DIhooR43qs2wKQ
提取码:mimz
1、将源码解压出来,然后放到你需要的项目下
2、pro文件下添加
include(soap/qtsoap.pri)
三、例程
借鉴:https://blog.youkuaiyun.com/liang19890820/article/details/51673800
我们以“获得腾讯QQ在线状态”为例,见:WebXml.com.cn,里面包含了大量的Web服务,例如:手机号码归属地查询,电子邮件地址验证、城市天气预报查询等。
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <qtsoap.h>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void onResponse(const QtSoapMessage &response);
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QtSoapHttpTransport *m_pHttp;
};
#endif // MAINWINDOW_H
mainwindow.c
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDebug"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_pHttp = new QtSoapHttpTransport(this);
connect(m_pHttp, SIGNAL(responseReady(const QtSoapMessage &)), this, SLOT(onResponse(const QtSoapMessage &)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::onResponse(const QtSoapMessage &response)
{
QString strXML = response.toXmlString();
qDebug()<<strXML;
QDomDocument doc;
doc.setContent(strXML);
// 接在在线状态
QDomNodeList nodeList = doc.elementsByTagName("qqCheckOnlineResult");
if (!nodeList.isEmpty())
{
QDomNode node = nodeList.at(0);
QString strResult = node.toElement().text();
QString strState("N/A");
if (QString::compare(strResult, "Y") ==0)
{
strState = QString("在线");
}
else if (QString::compare(strResult, "N") == 0)
{
strState = QString("离线");
}
else if (QString::compare(strResult, "E") == 0)
{
strState = QString("QQ号码错误");
}
else if (QString::compare(strResult, "A") == 0)
{
strState = QString("商业用户验证失败");
}
else if (QString::compare(strResult, "V") == 0)
{
strState = QString("免费用户超过数量");
}
qDebug()<<strState;
}
}
void MainWindow::on_pushButton_clicked()
{
QtSoapMessage message;
// 设置方法
message.setMethod("qqCheckOnline", "http://WebXml.com.cn/");
// 设置动作
m_pHttp->setAction("http://WebXml.com.cn/qqCheckOnline");
// 设置主机
m_pHttp->setHost("www.webxml.com.cn");
// 添加方法参数
QString strQQ = "511246";
message.addMethodArgument("qqCode", "", strQQ);
QString strXML = message.toXmlString();
qDebug()<<strXML;
// 提交请求
m_pHttp->submitRequest(message, "/webservices/qqOnlineWebService.asmx");
}
四、本机调试soap
网络调试助手打开tcp,端口:80
将上述代码中的
// 设置主机
m_pHttp->setHost("www.webxml.com.cn");
改成
// 设置主机
m_pHttp->setHost("192.168.1.79"); //这里改成自个电脑ip