webservice

C++调用webservice接口

 

1.准备要调用的webservice接口的wsdl地址,比如网上的查询天气接口:http://ws.webxml.com.cn/WebServices/WeatherWS.asmx?wsdl

2.准备gSOAP工具:将gsoap_2.8.100.zip解压,进入gsoap_2.8.100gsoap-2.8gsoapinwin32目录下(工具可以在这个网址下载:https://sourceforge.net/projects/gsoap2/files/gsoap-2.8/

3.将wsdl文件保存到win32目录下,如下;

 4.在该目录下打开cmd窗口(按住shift键,然后点击鼠标右键,选择“在此处打开命令窗口”),如下:

 5.在黑窗口中输入命令:wsdl2h -s WeatherWS.wsdl,点击回车生成WeatherWS.h头文件

 

6.继续在黑窗口输入命令:soapcpp2 -i -C -x -L WeatherWS.h -IE:CPLUSPLUSEXgsoap_2.8.100gsoap-2.8gsoapimport,点击回车生成一些头文件和源文件;(注意:我的gSOAP放在的是E:CPLUSPLUSEX下面,你们自己根据自己的路径输入)

7.打开Visual Studio 2012,在里面新建一个空项目

 8.将文件复制到“头文件”和“源文件”里面,如下所示(注意:应该先把所有文件都要复制到项目的文件夹里面,再从项目文件复制到“头文件”和“源文件”里面,其中的stdsoap2.h和stdsoap2.cpp在gsoap_2.8.100gsoap-2.8gsoap目录下。反正我是这样搞的,不然报些错误)

9.编写调用接口的代码,代码如下:

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <fstream>

//包含soap头文件
#include "soapH.h"
#include "soapStub.h"
#include "WeatherWSSoap.nsmap"
#include "soapWeatherWSSoapProxy.h"

using namespace std;

int main(int argc, char **argv) 
{
    //WebService的请求地址
    char* web_url = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx";
    //soap接口
    WeatherWSSoapProxy soap(SOAP_C_UTFSTRING);
    //构造输入参数
    _ns1__getWeather city_name;
    city_name.theCityCode = "";
    city_name.theUserID = "";
    
    //输出参数
    _ns1__getWeatherResponse weather_res;
    //调用接口方法getWeather 
    int xlt = soap.getWeather(web_url, NULL, &city_name, weather_res);
    //判断接口返回值, SOAPOK表示成功
    if (xlt == SOAP_OK)
    {
        // 获取返回结果
        ns1__ArrayOfString* aos = weather_res.getWeatherResult;

        // 打印返回结果
        int count = aos -> __sizestring;
        char **result = aos -> string;
        for (int i = 0; i < count; i++)
        {
            cout << result[i] << endl;
        }
    }

    getchar();
    return 0;

}
复制代码

10.跑起来,发现有结果,但有乱码。其实我入参传的空值,默认返回的应该是上海的天气。乱码问题目前没有解决,如果返回值是英文就没问题。

原文地址:https://www.cnblogs.com/xzh1993/p/13808904.html