電信provisioning系統中,常常需要與遠程服務器實時交換一些數據,以完成用戶的請求。由于簡單對象訪問協議(Simple Object Access Protocol, SOAP)的流行,許多涉及到第三方的應用,我們一般都比較樂意使用SOAP來開發。不過,由于可能涉及到公司的機密,本系列教程的開發實例盡量采用在網上已經公開的Web Service資源。
前面四節的教程,分別采用了股票信息和天氣預報的例子。而這兩個實例有一個共同點,SOAP響應消息的數據結構相對簡單,只需要按擬定的次序,事先約定返回數據代表的意義,就能夠實現無歧義的溝通。這就使得gSOAP能夠以字符串數組的形式,定義返回結果,再加上一個整型變量,指示返回結果的個數。
查看一下這兩個實例的soapStub.h,可以發現,它們的結果集定義正是這樣的:
{
int __sizestring; /* sequence of elements <string> */
char **string; /* optional element of type xsd:string */
};
但是,如果服務端返回的是一個相對復雜的結果集,事情就不那么好辦了。例如,一個提供外匯匯率的Web Service,服務端會同時返回日元、瑞郎、英鎊、歐元、澳元、加元、港幣合計七種貨幣兌換美元的匯率情報,每種匯率情報又包括貨幣代碼、當前匯率、漲跌幅、買入價、賣出價、時間戳等多個子項。顯然,這不是一個線性結構,而是一個樹形結構,就不能使用ArrayOfString來表示了。
這個案例的End point是:
http://webservice.webxml.com.cn/WebServices/ExchangeRateWebService.asmx
其WSDL是:
http://webservice.webxml.com.cn/WebServices/ExchangeRateWebService.asmx?wsdl
參考前面四節的內容,快速建立其存根程序,不再累述。
我們要實現的API是getExchangeRate,在soapStub.h中搜索,可以發現其返回結果集最終的定義是:
{
char *xsd__schema; /* required element of type xsd:schema */
char *__any;
};
僅僅是兩個字符串!于是,最初版本的外匯匯率客戶端程序只能這樣寫:
#include "soapH.h"
#include "ExchangeRateWebServiceSoap12.nsmap"
int conv_charset(const char *dest, const char *src, char *input, size_t ilen, char *output, size_t olen) {
iconv_t conv = iconv_open(dest, src);
if ( conv == (iconv_t) -1 )
return -1;
memset(output, 0, olen);
if ( iconv(conv, &input, &ilen, &output, &olen) )
return -1;
iconv_close(conv);
return 0;
}
int main(int argc, char **argv) {
if ( argc != 2 && argc != 3 ) {
printf("Usage: %s type [end_point]\n", argv[0]);
printf("\ttype = A : all rate\n");
printf("\ttype = B : basic rate\n");
printf("\ttype = C : cross rate\n");
exit(-1);
}
struct soap soap;
soap_init(&soap);
// don't set is OK
//soap_set_mode(&soap, SOAP_C_UTFSTRING);
struct _ns1__getExchangeRate request;
struct _ns1__getExchangeRateResponse response;
request.theType = argv[1];
char *endpoint = NULL;
if ( argc == 3 )
endpoint = argv[2];
if ( soap_call___ns3__getExchangeRate(&soap, endpoint, NULL, &request, &response) == SOAP_OK ) {
printf("%s\n", response.getExchangeRateResult->xsd__schema);
printf("----------\n");
int ilen = strlen(response.getExchangeRateResult->__any);
int olen = ilen * 2;
char *output = (char *) malloc(sizeof(char) * olen);
conv_charset("GBK", "UTF-8", response.getExchangeRateResult->__any, ilen, output, olen);
printf("%s\n", output);
free(output);
}
else {
soap_print_fault(&soap, stderr);
}
soap_destroy(&soap);
soap_end(&soap);
soap_done(&soap);
return 0;
}
其中,xsd__schema沒有中文字符,而__any含有中文字符,需要轉換成GBK編碼,具體可以參考前面兩節。
編譯執行,輸出結果如下圖:
可以看出,服務端返回的兩個長字符串實際上都是基于XML形式的。gSOAP能夠自動幫我們完成的也就到此為止,剩下的需要我們自力更生了。
不過,大家也不用頭疼,我們還有另外一個利器——libxml2!網上有很多關于libxml2的教程,所以我也不必多說,只要利用其中幾個函數和語句即可。
1. xmlParseMemory,字符串轉為XML文檔
2. xmlDocGetRootElement,獲取XML文檔根節點
3. xmlStrcmp,比較XML字符串,與strcmp差不多
4. curr = curr->xmlChildrenNode,XML節點指針指向第一個子節點
5. curr = curr->next,XML節點指針指向下一個兄弟節點
6. xmlNodeGetContent,獲取XML節點的內容
7. xmlFreeDoc,釋放節點,與free差不多
最終的外匯匯率客戶端程序如下:
#include <libxml/parser.h>
#include <libxml/xmlmemory.h>
#include "soapH.h"
#include "ExchangeRateWebServiceSoap12.nsmap"
#define FIELD_LEN 16
int conv_charset(const char *dest, const char *src, char *input, size_t ilen, char *output, size_t olen) {
iconv_t conv = iconv_open(dest, src);
if ( conv == (iconv_t) -1 )
return -1;
memset(output, 0, olen);
if ( iconv(conv, &input, &ilen, &output, &olen) )
return -1;
iconv_close(conv);
return 0;
}
int main(int argc, char **argv) {
if ( argc != 2 && argc != 3 ) {
printf("Usage: %s type [end_point]\n", argv[0]);
printf("\ttype = A : all rate\n");
printf("\ttype = B : basic rate\n");
printf("\ttype = C : cross rate\n");
exit(-1);
}
struct soap soap;
soap_init(&soap);
// don't set is OK
//soap_set_mode(&soap, SOAP_C_UTFSTRING);
struct _ns1__getExchangeRate request;
struct _ns1__getExchangeRateResponse response;
request.theType = argv[1];
char *endpoint = NULL;
if ( argc == 3 )
endpoint = argv[2];
if ( soap_call___ns3__getExchangeRate(&soap, endpoint, NULL, &request, &response) == SOAP_OK ) {
int len = strlen(response.getExchangeRateResult->__any);
xmlDocPtr pdoc = xmlParseMemory(response.getExchangeRateResult->__any, len);
xmlNodePtr root = xmlDocGetRootElement(pdoc);
xmlNodePtr curr = root;
while ( xmlStrcmp(curr->name, (const xmlChar *) "getExchangeRate") )
curr = curr->xmlChildrenNode;
for ( curr = curr->xmlChildrenNode; curr; curr = curr->next ) {
xmlNodePtr data;
for ( data = curr->xmlChildrenNode; data; data = data->next ) {
char ifield[FIELD_LEN];
char ofield[FIELD_LEN];
strcpy(ifield, xmlNodeGetContent(data));
if ( conv_charset("GBK", "UTF-8", ifield, strlen(ifield), ofield, FIELD_LEN) )
printf("%s\t%s\n", data->name, ifield);
else
printf("%s\t%s\n", data->name, ofield);
}
printf("\n");
}
xmlFreeDoc(pdoc);
}
else {
soap_print_fault(&soap, stderr);
}
soap_destroy(&soap);
soap_end(&soap);
soap_done(&soap);
return 0;
}
編譯時,需要鏈接libxml2庫,同時指定頭文件所在路徑:
gcc -O2 -o exchange exchange.c soapC.c soapClient.c ../../stdsoap2.c -I../.. -I/usr/include/libxml2 -L../.. -lgsoap -lxml2
執行結果(部分)如下:
-bash-3.2$ ./exchange B
Code JPY
Currency 日元
ClosePrice 87.08
DiffPercent -0.29%
DiffAmount -0.25
OpenPrice 87.5
HighPrice 87.71
LowPrice 87.04
Range 0.77%
BuyPrice 87.08
SellPrice 87.12
ChangeColor Green
DataTime 16:57:54
Code
CHF
Currency 瑞郎
ClosePrice 1.0552
DiffPercent 0.16%
DiffAmount 0.0017
OpenPrice 1.054
HighPrice 1.0552
LowPrice 1.0498
Range 0.51%
BuyPrice 1.0552
SellPrice 1.0556
ChangeColor Red
DataTime 16:57:52
http://blog.csdn.net/yui/archive/2010/07/26/5767494.aspx