windows qt 使用gsoap访问 WSDL 网络接口,以天气预报网站为示例

gsoap官方文档: https://www.genivia.com/docs.html
Web服务URL:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx
web服务WSDL:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?WSDL
1. gsoap 下载:
  • 下载链接:https://www.genivia.com/products.html ,下载开源版本(最右边一项,open source)
    windows qt 使用gsoap访问 WSDL 网络接口,以天气预报网站为示例_第1张图片

  • 解压到当前目录。

2.用gsoap生成接口文件
  • 打开cmd.exe
  • 进入 gsoap的解压目录 如:C:\Users\admin\Documents\projects\Beier-Pro\gsoap-2.8\gsoap\bin\win32(gsoap 有win64、win32等版本,建议使用win32)
  • 输入命令生成 接口文件 : myESSoap.h(可自定义文件名称)
    wsdl2h -o myESSoap.h http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?WSDL
    windows qt 使用gsoap访问 WSDL 网络接口,以天气预报网站为示例_第2张图片
  • 生成可调用的接口文件:
    **命令:soapcpp2.exe myESSoap.h -I …\import **
    windows qt 使用gsoap访问 WSDL 网络接口,以天气预报网站为示例_第3张图片
3.将生成的文件添加至项目中
  • 在qt 工程中创建文件夹,将上一步生成接口文件目录中,除wsdl2h.exe、soapcpp2.exe、myESSoap.h之外的其它文件都拷贝至此目录。
  • 拷贝 gsoap_2.8.122\gsoap-2.8\gsoap 下的 stdsoap2.cpp stdsoap2.h 至上一步所建目录中。
  • 拷贝之后项目目录结构如下:
    windows qt 使用gsoap访问 WSDL 网络接口,以天气预报网站为示例_第4张图片
  • 修改打开qt creator,修改.pro文件,将以下几个文件引入项目中:
SOURCES += \
    gSoapWheather/soapC.cpp \
    gSoapWheather/soapClient.cpp \
    gSoapWheather/stdsoap2.cpp \
    main.cpp \
    mysoap.cppS


HEADERS += \
    mysoap.h \
    gSoapWheather/myESSoap.h \
    gSoapWheather/soapH.h \
    gSoapWheather/soapStub.h \
    gSoapWheather/stdsoap2.h

INCLUDEPATH += ./gSoapWheather
  • 加载ws2_32.lib库,在.pro文件中最后面添加如下代码:
LIBS += -lws2_32    

*main.cpp

#include 
#include "mysoap.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MySoap w;

    return a.exec();
    
}
  • mysoap.cpp
#include "mysoap.h"
#include "gSoapWheather/soapH.h"
#include "gSoapWheather/soapStub.h"
#include "gSoapWheather/stdsoap2.h"
#include "gSoapWheather/WeatherWSSoap.nsmap"
#include 

MySoap::MySoap(QObject *parent)
    : QObject(parent)
{
    struct soap m_soap;
    soap_init(&m_soap);
    soap_set_mode(&m_soap, SOAP_C_UTFSTRING); //解决gsoap中文乱码问题
    _ns1__getSupportCityString req;           // 传递数据, 和接口名对应  _ns1__xxxxx
    _ns1__getSupportCityStringResponse res;   // 接收数据, 和接口名对应  _ns1__xxxxxResponse

    QString url("http://ws.webxml.com.cn/WebServices/WeatherWS.asmx");
    QString acton("http://www.w3.org/2003/05/soap-envelope");
    std::string str = "shanghai";
    req.theRegionCode = &str; //接口参数
    int ErrNo = soap_call___ns1__getSupportCityString(&m_soap, url.toUtf8(), acton.toUtf8(), &req, res);

    if (ErrNo == SOAP_OK) {
        foreach (auto val, res.getSupportCityStringResult->string) {
            qDebug() << "res:" << val.data();
        }
    }
    if (m_soap.error != 0) {
        //获取错误提示
        QString errStr = QString::fromLocal8Bit(*soap_faultstring(&m_soap));
        qDebug() << "错误提示: " << errStr << "error code:" << m_soap.error;
    }
    soap_end(&m_soap);
    soap_done(&m_soap);
}

参考:https://blog.csdn.net/chen1231985111/article/details/126125568,感谢!

你可能感兴趣的:(Windows,qt,windows,websocket)