C++调用WebService

1. gSOAP是一个开源的项目,用它可以方便的使用c/c++地进行SOAP客户端和服务器端编程,而不必了解xml和SOAP协议的细节

wsdl2h.exe: 编译wsdl文件生成c/c++头文件

-o 文件名,指定输出头文件 
-n 名空间前缀 代替默认的ns 
-c 产生纯C代码,否则是C++代码 
-s 不要使用STL代码 
-t 文件名,指定type map文件,默认为typemap.dat 
-e 禁止为enum成员加上名空间前缀

soapcpp2.exe: gSOAP编译器,编译头文件生成服务器和客户端都需要的c/c++文件(默认使用STL,需要stlvector.h)

-C 仅生成客户端代码 
-S 仅生成服务器端代码 
-L 不要产生soapClientLib.c和soapServerLib.c文件 
-c 产生纯C代码,否则是C++代码(与头文件有关) 
-I 指定import路径(见上文) 
-x 不要产生XML示例文件 
-i 生成C++包装,客户端为xxxxProxy.h(.cpp),服务器端为xxxxService.h(.cpp)

2. 生成存客户端存根程序和框架
wsdl2h -o xx.h http://192.168.40.8:88/GMM?wsdl 

或者 wsdl2h -o xx.h http://js.gps163.com:8994/Server/CsService.svc?wsdl
soapcpp2 -C -L -x -i xx.h (soapcpp2 xx.h -C -I D:\gsoap-2.7\gsoap\import)

3. 把如下生成的文件添加到项目:
soapStub.h,soapH.h,stdsoap2.h

soapC.cpp,soapClient.cpp,stdsoap2.cpp

soapBasicHttpBinding_USCOREIGMMProxy.cpp

soapBasicHttpBinding_USCOREIGMMProxy.cpp

BasicHttpBinding_USCOREIGMM.nsmap

wsock32.lib

4. 调用

#include "soapBasicHttpBinding_USCOREIGMMProxy.h"
#include "BasicHttpBinding_USCOREIGMM.nsmap"

//代理方式调用不需要初始化
//struct soap xxSoap;
//soap_init(&xxSoap);

//代理类对象
xxWebServiceSoap xxProxy; 

//设置头信息
//SOAP_ENV__Header envHeader;
//xxProxy.soap->header = &envHeader;

//web服务对象
_ns1__xx xx; 

//web服务结果对象 
_ns1__xxResponse xxResponse;

//调用WebService方法


5. 使用的例子:

 1 CString CGetLocation::GetLocation(int iLon, int iLat)

 2 {

 3     CString strAddress = _T("");

 4 

 5     struct soap soap1 ;

 6     soap_init(&soap1);

 7     soap_set_mode(&soap1, SOAP_C_MBSTRING);

 8 

 9     BasicHttpBinding_USCOREIGMMProxy locationService(soap1);

10 

11     _ns3__GetLocation    getLocation;

12     _ns3__GetLocationResponse getLocationRes;

13 

14     bool blOffset = false;

15     getLocation.Latitude = &iLat;

16     getLocation.Longitude = &iLon;

17     getLocation.blOffset = &blOffset;

18 

19     int nOK = -1;

20 

21     try

22     {

23         nOK = locationService.GetLocation(strWCFUrl.c_str(), NULL, &getLocation, &getLocationRes);

24     }

25     catch (...)

26     {

27         CString strLog;

28         strLog.Format(_T("GetLocation try catch error : %d\r\n"), GetLastError());

29         TRACE(strLog);

30         return strAddress;

31     }

32 

33 

34     if (nOK != SOAP_OK)

35     {

36         char szError[255] = {0};

37         soap_sprint_fault(&soap1, szError, 255);

38 

39         CString strLog;

40         strLog.Format(_T("SOAP Error: %s\r\n"), szError);

41         TRACE(strLog);

42         return strAddress;

43     }

44 

45     if (getLocationRes.GetLocationResult == NULL || (*getLocationRes.GetLocationResult).empty())

46     {

47         CString strLog;

48         strLog.Format(_T("SOAP Result: Error\r\n"));

49         TRACE(strLog);

50         return strAddress;

51     }

52 

53     strAddress = (*getLocationRes.GetLocationResult).c_str();

54     return strAddress;

55 }

 

你可能感兴趣的:(webservice)