和第三方对接的时候对方只给了一个WSDL文件,让我调用他们的接口,起初完全不知道怎么弄,后来看到需求说明要求使用soap的方式通信;
然后网上找了一番,都是c++使用gsoap完成add的例子;参照他们例子终于完成了客户端和服务端的编写
soapcpp2.exe -c++ add.h 生成一系列文件,具体的参见 http://www.cppblog.com/qiujian5628/archive/2008/06/19/54019.html
前辈门描述的非常清楚;
#include <iostream> #include <string> #include "addServer.h" #include "add.nsmap" #include "stdsoap2.h" #include "soapH.h" #include "soapStub.h" #pragma comment(lib,"wsock32.lib") #pragma comment( linker, "/subsystem:windows /entry:mainCRTStartup" ) // 为了程序不弹出dos界面 int http_get(struct soap *soap); int add__ns(struct soap *add_soap, int num1, int num2, int *sum); int main(int argc, char* argv[]) { int m, s; /* master and slave sockets */ struct soap add_soap; add_soap.fget = http_get;// 设置soap.fget回调函数 soap_init(&add_soap); add_soap.fget = http_get; if (argc < 2) { printf("usage: %s <server_port> \n", argv[0]); exit(1); } else { m = soap_bind(&add_soap, NULL, atoi(argv[1]), 100); if (m < 0) { soap_print_fault(&add_soap, stderr); exit(-1); } fprintf(stderr, "Socket connection successful: master socket = %d\n", m); for (;;) { s = soap_accept(&add_soap); if (s < 0) { soap_print_fault(&add_soap, stderr); exit(-1); } fprintf(stderr, "Socket connection successful: slave socket = %d\n", s); soap_serve(&add_soap);//该句说明该server的服务 soap_end(&add_soap); } } return 0; } //server端的实现函数与add.h中声明的函数相同,但是多了一个当前的soap连接的参数 int add__ns(struct soap *add_soap, int num1, int num2, int *sum) { *sum = num1 + num2; return 0; } int http_get(struct soap *soap) { FILE*fd = NULL; // 发布web server的时候就是将程序放在cmd中运行,记得将wsdl文件和exe文件放在以前 fd = fopen("./add.wsdl", "rb"); //open WSDL file to copy if (!fd) { return 404; //return HTTP not found error } soap->http_content = "test/xml"; //HTTP header with text /xml content soap_response(soap,SOAP_FILE); for(;;) { size_t r = fread(soap->tmpbuf,1, sizeof(soap->tmpbuf), fd); if (!r) { break; } if (soap_send_raw(soap, soap->tmpbuf, r)) { break; //cannot send, but little we can do about that } } fclose(fd); soap_end_send(soap); return SOAP_OK; }
编译完成后,在cmd中运行,然后使用soapUI来测试此服务器的正确即可,参见 http://boyun.sh.cn/blog/?p=1076
至于客户端网上一大堆教材,值得注意的是有些WSDL生成的类需要去重载构造函数,否则就是调用了默认的构造函数;
目前尚未解决的问题就是打开Localhost:8989后xml文件是下载打开的方式,不能直接显示到页面上