您的位置:首页 > 编程语言 > C语言/C++

gsoap(C/C++调用webservice)

2011-05-26 18:00 281 查看



C/C++调用Web Service需要用到soap库,一般使用的有gsoap和axis
cpp两种实现,这里使用gsoap来调用。gsoap是sourceforge上的一个开源项目,目前版本是2.7.6c,使用简单,可以在
linxu、windows、mac多种平台上使用。gsoap的主页地址是http://gsoap2.sourceforge.net/

gsoap使用步骤

gsoap提供了两个有用的工具,帮助我们生成代理类。

实际用到的源码

gsopa所有源码在stdsoap2.c /stdsoap2.cpp和stdsoap2.h中,编译目标文件时要根据实际使用的语言来选择stdsoap2.c/cpp

使用wsdl2h生成函数描述

wsdl2h -c -o message.h http://***/messageservice.asmx?wsdl
message.h表示根据http://***/messageservice.asmx?wsdl
输出函数描述文件为message.h

-c 参数表示用纯c语言来实现,如果不加-c,则用c++语言来实现

使用soapcpp2来生成代理函数

下面的命令根据刚产生的message.h文件来生成代理类/函数:

soapcpp2 -c message.h

执行后,会产生若干个h文件和c文件,里面包含了对远程函数的封装。

本例中生成了以下文件: soapH.h soapServer.c soapServerLib.c soapClient.c soapClientLib.c soapStub.h soapC.c MessageServiceSoap.nsmap

做为web service调用方,实际使用到的stdsoap2.c soapC.c soapClient.c这几个文件(包括对应头文件),MessageServiceSoap.nsmap实际上是一个头文件,定义了soap相应的namespace.

使用生成的代理类/函数

将代码保存为client.c

#include "soapH.h"

#include "MessageServiceSoap.nsmap"

int main()

{

struct soap *soap = soap_new();

struct _ns1__SendSMSResponse out;

char * url = "http://***/MessageService.asmx
";

struct _ns1__SendSMS msg;

msg.sender = "900";

msg.receiver = "mic";

msg.title = "test";

msg.msgInfo = "testinfo";

msg.messageType = 0;

soap_set_mode(soap, SOAP_C_UTFSTRING); //设置soap编码为UTF-8,防止中文乱码

if(soap_call___ns1__SendSMS(soap, url, "http://***/common/message/SendSMS

", &msg, &out) == SOAP_OK)

{

printf("OK");

}

}

编译目标

gcc -o msg stdsoap2.c soapC.c soapClient.c client.c stdsoap2.c

更多使用例子,可以查看gsoap附带的sample目录。

编码转换的例子,保证使用utf8传输

int GBKtoUTF8(char *fromstr,size_t fromlen,char *tostr,size_t tolen)

{

int r;

iconv_t cd;

if ((cd = iconv_open("GBK","UTF-8")) == (iconv_t)-1) {

fprintf(stderr, "iconv_open from UTF to GBK error: %s/n", strerror(errno));

return -1;

}

r = iconv(cd,&fromstr,&fromlen,&tostr,&tolen);

if (r < 0) {

fprintf(stderr, "iconv from UTF to GBK error: %s/n", strerror(errno));

iconv_close(cd);

return -2;

}

iconv_close(cd);

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: