工作中需要用c++来调用第三方的webservice接口,于是使用了gsoap工具。为了初步掌握gsoap的使用方法,这里写了一个demo程序来完成对于天气预报查询接口的调用。
安装好gsoap工具,然后使用make gsoap命令编译。
/*makefile文件如下*/
#make file for testing gsoap all:test GSOAP_ROOT = /usr/share/gsoap/import WSDL_FILES = $(wildcard *.wsdl) OBJS = $(patsubst %.cpp,%.o,$(wildcard *.cpp)) CXX = /usr/bin/g++ CXXFLAGS = -g # -fno-use-linker-plugin LIBS = -lgsoap++ ifeq ( ,$(WSDL_FILES)) WSDL_FILES = http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl endif wsdl: wsdl2h $(WSDL_FILES) -t /usr/share/gsoap/WS/typemap.dat -o weather.h # -C only client,-I import path,-L no soap*Lib.c file,-x no xml file gsoap:wsdl soapcpp2 -iCLx -I $(GSOAP_ROOT) weather.h test:$(OBJS) $(CXX) $(CXXFLAGS) $(LIBS) $^ -o $@ clean: @rm -rf $(OBJS) test
编译完成后会生成 WeatherWebServiceSoap.nsmap、soapWeatherWebServiceSoapProxy等之类的文件。
将这些文件放到你的项目中,然后创建一个调用天气查询的demo程序:test.cpp。
#include "WeatherWebServiceSoap.nsmap"
#include "soapWeatherWebServiceSoapProxy.h"
#include <string>
#include <iostream>
using namespace std;
void showResult(ns1__ArrayOfString* aos){
for (vector<string>::iterator
itr = aos->string.begin(), itr_end = aos->string.end();
itr != itr_end; ++itr)
{
string str = *itr;
const char* str2 = str.c_str();
std::cout << str2 << std::endl;
}
}
int main(int argc, char** argv)
{
struct soap soap;
soap_init(&soap);
//soap_set_imode(&soap, SOAP_C_UTFSTRING);
_ns1__getSupportCity request;
std::string provinceName = "四川";
request.byProvinceName = &provinceName;
_ns1__getSupportCityResponse response;
WeatherWebServiceSoapProxy* serviceProxy = new WeatherWebServiceSoapProxy(SOAP_C_UTFSTRING, SOAP_C_UTFSTRING);
/*获取支持的城市名*/
int result=serviceProxy->getSupportCity(&request,&response);
if (SOAP_OK==result)
{
showResult(response.getSupportCityResult);
}
else
{
std::cout << "error:" << serviceProxy->soap_fault_string() << std::endl << std::endl;
}
/*查询城市的天气*/
std::string cityName = "攀枝花";
_ns1__getWeatherbyCityName weatherRequest;
weatherRequest.theCityName = &cityName;
_ns1__getWeatherbyCityNameResponse weatherResponse;
int ret=serviceProxy->getWeatherbyCityName(&weatherRequest, &weatherResponse);
if (SOAP_OK==ret){
showResult(weatherResponse.getWeatherbyCityNameResult);
}
else
{
std::cout << "error:" << serviceProxy->soap_fault_string() << std::endl;
}
delete serviceProxy;
return 0;
}使用make 命令编译程序。执行可执行程序,结果如下:
原文地址:http://11009639.blog.51cto.com/10999639/1744664