C + + Request Web service and XML parsing

Source: Internet
Author: User
Tags base64 gettext wsdl

1. Open Source Library for C + + parsing xml

The parsing of XML in the project uses an open-source third-party library,TinyXML; the model of this parsing library is generated in the XML file and then in memory DOM model so that we can easily traverse the XML Tree.

The DOM model, the Document object model, divides the entire document into elements such as books, chapters, sections, paragraphs, and so on, and uses a tree structure to represent the sequential relationships between these elements and the nested containment relationships. Let 's take a look at the correspondence between the main classes in TinyXML and the XML documents, which is the main class in TinyXML class diagram, which reflects the static relationship between the various classes.

Tixmlbaseis the base class for all classes,Tixmlnode,Tixmlattributetwo classes are inherited from aTixmlbaseclass, whereTixmlnodeclass refers to all the<...>...<.../>including the content, whileXMLthe nodes in this paper are divided into the following aspects: declarations, annotations, nodes, and text between nodes, soTixmlnodeon the basis of these several classes are derivedtixmlcomment,tixmldeclaration,tixmldocument,tixmlelement,Tixmltext,Tixmlunknown, respectively, to indicate the specificXMLwhich part of the. Tixmlattributeclass differs fromTixmlnode, it refers to the content inside the angle brackets, like<...***=...>, where***is a property that uses aXMLThe documentation specifically describes:

1.<?xml version= "1.0"  encoding= "UTF-8"?>  2.<phonebook>  3.     <!--one item behalfs one contacted person.-->  4.     <item>  5.        <name> Miaomaio</name>  6.    <addr>shaanxi xi ' an</addr>   7.    <tel>13759911917</tel>  8.    < email>[email protected]</email>  9.    </item>   10.    <item>  11.        <name >gougou</name>  12.    <addr>Liaoning Shenyang</addr>   13.    <tel>15840330481</tel>  14.     <email>[email protected]</email>  15.    </item>  16.      <!--more contacted persons.-->  </phonebook> 

L like Tixmldeclaration refers to <?xml version= "1.0" encoding= "UTF-8"?

L like Tixmlcomment refers to <!--one item Behalfs one contacted Person.-->, <!--more contacted Persons.-->

L like Tixmldocument refers to the entire XML document,

L like Tixmlelement refers to <phonebook>, <item>, <name>, <addr> and so on these nodes,

L like Tixmltext refers to ' Gougou ', ' 15840330481 ' which are sandwiched between <item> and </item>, <name> and </name>, <addr> and </addr> text between the texts,

L like Tixmlattribute refers to <?xml version= "1.0" encoding= "UTF-8"?> node in version, encoding,

L Besides that is tixmlunknown.

1) Read the XML file
!xml file read, the impersonation call interface returns char * string Filebuf *pbuf;ifstream filestr;long Size;char *buffer;filestr.open (xml_example_file_ NAME, ios::binary);p buf = Filestr.rdbuf (); size = Pbuf->pubseekoff (0,ios::end,ios::in);p buf->pubseekpos (0, iOS: : in), buffer = new Char[size];p buf->sgetn (buffer, size), Filestr.close (),//! get correlation value from XML string Strcreationtime; String strjobid;string strjobtype;string strjobname;string strjobleader; Tixmldocument *xmldocument = new Tixmldocument () xmldocument->parse (buffer, 0, tixml_default_encoding); Tixmlelement *rootelement = Xmldocument->rootelement (); Tixmlelement *fileheaderelement = Rootelement->firstchildelement (); Tixmlelement *filebodyelement = Fileheaderelement->nextsiblingelement (); for (tixmlelement *nodeElement = Fileheaderelement->firstchildelement (); Nodeelement; Nodeelement = Nodeelement->nextsiblingelement ()) {string strelementkey = Nodeelement->value (); if ( Strelementkey.compare (xml_parse_creation_time) = = 0) {strcreationtime = Nodeelement-> GetText ();}} for (Tixmlelement *nodeelement = Filebodyelement->firstchildelement (); nodeelement; nodeelement = nodeElement-> Nextsiblingelement ()) {string strelementkey = Nodeelement->value (); if (Strelementkey.compare (xml_parse_job_id) = = 0) {strjobid = Nodeelement->gettext ();} if (Strelementkey.compare (xml_parse_job_type) = = 0) {Strjobtype = Nodeelement->gettext ();} if (Strelementkey.compare (xml_parse_job_name) = = 0) {strjobname = Nodeelement->gettext ();} if (Strelementkey.compare (xml_parse_job_leader) = = 0) {Strjobleader = Nodeelement->gettext ();}}
2) Create and generate XML files

Take the following XML file As an example:

<?xml version= "1.0" encoding= "gb2312" ><InterFaceFile>     <FileHeader>          <MessageType> proxymiddlewarejobsearch</messagetype>          <Originator>WetLand</Originator>  < recipient>platform</recipient>          <creationtime>2014-9-18 10:25:20</creationtime>     </FileHeader>     <FileBody>          <UserName>...</UserName>          <userroleid>13 </UserRoleID>           <JobType></JobType>      </FileBody></InterFaceFile>

//! Build XML string Tixmldocument *pdoc = new Tixmldocument; Tixmldeclaration *pdeclaration = new Tixmldeclaration ("1.0", "gb2312", "" ");pD Oc->linkendchild (pdeclaration); Tixmlelement *peleroot = new Tixmlelement ("Interfacefile");pD Oc->linkendchild (peleroot); Tixmlelement *pelefileheader = new Tixmlelement ("Fileheader"); Tixmlelement *pelefilebody = new Tixmlelement ("Filebody");p eleroot->linkendchild (pelefileheader);p eleroot-> Linkendchild (Pelefilebody); Tixmlelement *pelemessagetype = new Tixmlelement ("MessageType"); Tixmlelement *peleoriginator = new Tixmlelement ("originator"); Tixmlelement *pelerecipient = new Tixmlelement ("Recipient"); Tixmlelement *pelecreationtime = new Tixmlelement ("CreationTime");p Elefileheader->linkendchild (PEleMessageType) ;p elefileheader->linkendchild (peleoriginator);p elefileheader->linkendchild (pelerecipient); Pelefileheader->linkendchild (Pelecreationtime); Tixmltext *pelemessagetypetext = new Tixmltext ("Proxymiddlewarejobsearch"); Tixmltext *peleoriginatOrtext = new Tixmltext ("wetland"); Tixmltext *pelerecipienttext = new Tixmltext ("Platform"); Tixmltext *pelecreationtimetext = new Tixmltext ("2014-9-18 10:25:20");p Elemessagetype->linkendchild ( Pelemessagetypetext);p eleoriginator->linkendchild (peleoriginatortext);p Elerecipient->linkendchild ( Pelerecipienttext);p elecreationtime->linkendchild (pelecreationtimetext);//! Tixmlelement *peleusername = new Tixmlelement ("UserName"); Tixmlelement *peleuserroleid = new Tixmlelement ("Userroleid"); Tixmlelement *pelejobtype = new Tixmlelement ("JobType");p elefilebody->linkendchild (peleusername);p elefilebody- >linkendchild (Peleuserroleid);p elefilebody->linkendchild (Pelejobtype); Tixmltext *peleusernametext = new Tixmltext ("..."); Tixmltext *peleuserroleidtext = new Tixmltext ("13"); Tixmltext *pelejobtypetext = new Tixmltext ("");p Eleusername->linkendchild (peleusernametext);p eleuserroleid-> Linkendchild (Peleuserroleidtext);p elejobtype->linkendchild (pelejobtypetext);pD oc->savefile ("E:/houqd.xml "); 

3) generating an XML string

To generate the XML string Simply replace the pdoc->savefile ("E:/houqd.xml") as follows:

! Generate string String Tixmlprinter printer;pdoc->accept (&printer); string strrequest (printer. CSTR ());
2. C + + Tune Soap's Open Source Library

We use gSOAP as an open source Web service implementation framework that can be downloaded from the Web to open source code implementations. :http://gsoap2.sourceforge.net/ Generic downloaded gSOAP toolkit already contains the build web Two tools (executables) required for service clients: Wsdl2h.exe and Soapcpp2.exe,windows development packages typically under GSOAP/BIN/WIN32, WSDL2H does not support SSL by default. That is, you cannot access the HTTPS site, and if you want to support more features such as SSL, you will need to reconfigure the gSOAP toolkit yourself to generate new Wsdl2h.exe and soapcpp2.h. Here, I am using the native file.

Related reference:http://blog.csdn.net/zhaiwenjuan/article/details/6590941

1) gSOAP generate local agent

1> generating the corresponding header file based on WSDL

Gets the WSDL file for the Web service from the Web services provider , usually a URL, such as:http://www.somewebservice.com/Service?Wsdl, of course, can also be a Wsdl form of an XML file.

Using gSOAP's Wsdl2h.exe, a header file is generated from WSDL based on the C + + syntax structure.

Example: Wsdl2h.exe-s-o Service.h http://www.somewebservice.com/Service?Wsdl

After this step is finished, you will get a header file, such as: Service.h

The purpose of this step is to implement a data map of the WSDL file to the. h file.

2> generating related proxy files based on generated header files

Use gSOAP 's precompiled soapcpp2.exetogenerate stub files based on the header files obtained in the previous step soapStub.h And the client code framework:

such as:soapcpp2.h-i-x-c-L Service.h

This step will get several . Nsmap,. h , and . cpp files. The purpose of this step is to generate the corresponding underlying communication code.

2) gSOAP call WebService interface

Add the files generated in the previous steps to the project and include the header file for the response, using the following method of invocation:

String Strrequest (printer. CSTR ());//!web Service Tune interface string strwebserviceaddr = "http://172.16.10.209:8080/HDHT_J2EE/services/ PROXYMIDDLEWAREJOB?WSDL "; Proxymiddlewarejobhttpbindingproxy *proxy = new Proxymiddlewarejobhttpbindingproxy (); _ns1__ Proxymiddlewarejobsearch Inputparam;_ns1__proxymiddlewarejobsearchresponse outputparam;inputparam.in0 = const_cast <char *> (Strrequest.c_str ());p Roxy->proxymiddlewarejobsearch (Null,strwebserviceaddr.c_str (), & Inputparam, Outputparam); string strresult = Outputparam.out;
3. Problems in the process of the tune-up 1) parameter transfer problem

Here, when using the Web service invocation interface, according to the previous idea (in PHP Web Service call method), for the time being called in C + + as a direct transfer of parameters, For example, when the Proxymiddlewarejobsearch interface is called above, it receives an XML-formatted string and returns an XML-formatted string, so when it is first used, it is invoked as follows:

Proxy->proxymiddlewarejobsearch (NULL, Strwebserviceaddr.c_str (), Strrequest, Strresult), the string form used, the result has been an error, This means that you cannot convert a const char * to a _ns1__proxymiddlewarejobsearch * form, and it should be used as follows in later application:

_ns1__proxymiddlewarejobsearch Inputparam; //! Represents input

_ns1__proxymiddlewarejobsearchresponse Outputparam; ! Represents the output

Inputparam.in0 = Const_cast<char *> (strrequest.c_str ()); ! Enter the first parameter,

If the interface requires a second parameter, it is called by: Inputparam.in1 = ...

string strresult = Outputparam.out; //! The return of the result after the call.

2) Chinese garbled problem

Workaround: In Java to build the Web service side, before returning the string, base64 encryption, and then C + + as the client of the Web service after the method is called, the string is decrypted first Base64, so there is no garbled problem.

C + + implementation Base64 's code reference link:

Http://www.cnblogs.com/phinecos/archive/2008/10/10/1308272.html

C + + Request Web service and XML parsing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.