Writing Web Services Client Applications Using Visual C
Abstract:. XML Web Services is rapidly becoming the technology of choice for distributed application and application-integration, over Internet The caller application uses the standard protocol (such as HTTP or SMTP) to send specially-formatted XML messages (known as SOAP request envelope );. the server application in turn does the processing and sends back the results also as specially formatted XML message (known as SOAP response envelope) The standards-based notion of Web Services enables these two applications; possibly residing on two totally different platforms, and written using varied programming languages and tools;. to interact without and platform- or programming language-worries XML Web Services is receiving more and more vendor and tools support, and the technology itself is maturing rapidly Microsoft, IBM, and others are working. To Define The Essential Layers (Such As Security, Transaction-Support, Web Services Reliability) Over Web Services. thi S Article Illustrates Writing XML Web Services Client Applications In Visual C , Using Microsoft XML Core Services (or Msxml), Microsoft Soap Toolkit Version 3, and Pocketsoap.
The first example uses the MSXML XMLHTTP component to invoke a Web Service written using Apache SOAP. The second example uses the MSXML ServerXMLHTTP component to invoke a Web Service written using (ASP) .NET. This example illustrates calling a Web Service using HTTP GET, HTTP POST, and SOAP. The third example uses Microsoft SOAP Toolkit Version 3 high-level API to invoke a Web Service written using GLUE. The fourth example uses Microsoft SOAP Toolkit Version 3 low-level API to invoke a Web Service written using (ASP ) .NET. The fifth, and final, C sample application illustrates using PocketSOAP to call a .NET Web service.All the sample applications in this article are Win32 console applications written using C and created using Microsoft Visual Studio 6.0. The first two applications use MSXML 4, next two (third and fourth) sample applications use SOAP Toolkit version 3, and the fifth application uses PocketSOAP. Be sure to download and install these libraries to successfully run the code samples provided with this article Author:. Darshan Singh (Managing Editor, PerfectXML.com) Last Updated: February 02, 2003 Download: CPPSOAP.zip (353 KB ZIP file) 1. Using MSXML XMLHTTP MSXML, the premier XML processing component from Microsoft, IS SHIPPED with VARIOUS VERSIONS OF Internet Explorer (for Example, IE 6.0 Ships MSXML VERSION 3 SP2); and is also available as a seat. If you are Writing a C
desktop client application and need to call a Web Service, one option is to use the XMLHTTP component inside MSXML. XMLHTTP, a COM wrapper around WinInet (the core HTTP API used by Internet Explorer), allows sending HTTP GET and POST requests and process the response. XMLHTTP is designed to be used on the client-side, and should not be used inside server applications to send HTTP requests to other servers. If you are writing a server-side application, and need to call a Web Service, refer to . example 2 below, which uses ServerXMLHTTP This first sample application uses MSXML XMLHTTP to POST a SOAP request to the Weather Temperature Web Service on the XMethods Web site The header file (XMLHTTP1.h):?. # ifndef _XMLHTTP1_H_ # define _XMLHTTP1_H_
#include
#import
USING NAMESPACE MSXML2;
#define check_hr (hr) {if (failed (hr)) {throw -1;}}
// SOAP EndPoint URL
Static const tchar * const g_lpszsoapendpointURL =
_T ("http://services.xmethods.net:80/soap/servlet/rpcrouter");
// SOAP REQUEST to Be Posted
Static const tchar * const g_lpszsoapreq = _t (
"XMLns: XSI = 'http://www.w3.org/1999/xmlschema-instance'" "XMLns: XSD = 'http://www.w3.org/1999/xmlschema'>" " " "SOAP-ENV: EncodingStyle = 'http://schemas.xmlsoap.org/soap/ENCODING/'>" " ns1: getTemp>" " Soap-env: body>" " Soap-env: envelope>"); # endif // _xmlhttp1_h_the source code file (xmlhttp1.cpp) #include "stdafx.h" #include "xmlhttp1.h" / / -------------------------------------------------------------------------------------------- ------------------------------ // Function Uses XMLHTTP to Post A Soap Request to the Temprate Web Service // and then uses msxml Dom to process the soap response XML text. / / -------------------------------------------------------------------------------------------- ------------------------------ Float CallwebService (LPCTSTR SZZIPCODE) { Float fTemprature = -999; Uses_Conversion; // SOAP Request envelop to be posted TCHAR SZSOAPREQ [MAX_PATH * 2] = {0}; Sprintf (SzsoapReq, G_LpszsoapReq, Szzcode); // Printf (SzsoapReq); // Create an Instance of Xmlhttp Class CComptr HRESULT HR = SPXMLHTTP.COCREATEINSTANCE (CLSID_XMLHTTP40); Check_hr (hr); // Initialize The Synchronous http post request HR = SPXMLHTTP-> Open (_BSTR_T (_T ("post"), g_lpszsoapendpointURL, variant_false); Check_hr (hr); // set the required content-type header HR = SPXMLHTTP-> SetRequestHeader (_bstr_t (_T ("content-type")), _bstr_t (_t ("text / xml")))); Check_hr (hr); // send the post request, along with the soap request envelope text HR = SPXMLHTTP-> Send (_BSTR_T (SzsoapReq)); Check_hr (hr); IF (200 == SPXMLHTTP-> Status) // Success { // Using MSXML DOM to Process Soap Response XML Text CCOMQIPTR CComptr SpResponsexmldoc = SPXMLHTTP-> Responsexml; SpResultNode = spresponsexmldoc-> selectsinglenode (_bstr_t (_t ("// return"))) IF (SpResultNode.p! = null) { FTEMPRATURE = SpResultNode-> NodetyPedValue; } Else { Printf (_t ("/ Nerror:% S / N"), W2A (SPXMLHTTP-> statustext); } Return fTemprature; } // main, the entry point function Int main (int Argc, char * argv []) { IF (Argc <2) {// insufficient parameters Printf (_t ("/ nxmlhttp1.exe: sample web service client to get the temprature for the given zipcode./N"); Printf (_t ("/ nusage: /txmlhttp1.exe Return -1; } Try { HRESULT HR = Coinitialize (NULL); Check_hr (hr); Float fTemp = CallwebService ((lpctstr) argv [1]); IF (fTemp! = -999) Printf ("The Temprature At Zipcode% s IS% .2f Fahrenheit./npress Enter to Continue ...", Argv [1], FTEMP; Else Printf (_t ("/ Nerror: Invalid Zipcode or Failed to Get The Temprature At Zipcode% s." "/ NPRESS ENTER to Continue ..."), Argv [1]); } Catch (int) { // Todo: Error Handling Printf (_T ("exception raised!"); } Couninitialize (); GetChar (); Return 0; } Output:. The header file declares the #import statement so that we can use MSXML4, and declares couple of constant strings (the SOAP endpoint URL and the SOAP request envelope) The main function in the CPP file calls a supporting function CallWebService and passes it the value of the command line parameter (the zip code). The supporting function CallWebService then formats the request SOAP envelope and posts it to the SOAP endpoint URL. The responseXML property contains the response SOAP envelope and the above application uses MSXML DOM and XPath to get the result value. 2. Using MSXML ServerXMLHTTP If you are writing a server-side application (such as an ISAPI DLL or a COM DLL to be loaded on the server side), and need to invoke a XML Web Service, you can use MSXML ServerXMLHTTP component. The following sample C application illustrates using MSXML ServerXMLHTTP to invoke a .NET Web Service, either by sending HTTP GET request, or HTTP POST request, or posting SOAP and processing the SOAP response This sample application invokes the Weather Info XML Web Service to get the detailed weather information for any given valid US zip code The header file (ServerXMLHTTP1.h):.. # Ifndef _SERVERXMLHTTP1_H_ # define _SERVERXMLHTTP1_H_ #include #import USING NAMESPACE MSXML2; #define check_hr (hr) {if (failed (hr)) {throw -1;}} / / -------------------------------------------------------------------------------------------- ------------ Static const tchar * const g_lpszgeturl = _T ("http://www.ejse.com/weatherservice/service.asmx/getweatherinfo?zipcode=%s"); / / -------------------------------------------------------------------------------------------- ------------ Static const tchar * const g_lpszpostURL = _T ("http://www.ejse.com/weatherservice/service.asmx/getWeatherinfo"); // ------------------------- ------------------------------- Static const tchar * const g_lpszsoapendpointURL = _T ("http://www.ejse.com/weatherservice/service.asmx"); Static const tchar * const g_lpszsoapaction = _T ("http://ejse.com/weatherservice/getweatherinfo"); Static const tchar * const g_lpszsoapreq = _T (" Xml version = '1.0' encoding = 'UTF-8'?>" "XMLns: xsd = 'http://www.w3.org/2001/xmlschema'" "XMLns: soap = 'http://schemas.xmlsoap.org/soap/envelop/'>" " " " GetWeatherinfo>" " soap: body>" " soap: envelope>"); / / -------------------------------------------------------------------------------------------- ------------ Static const tchar * const g_lpszxpathselns = _T ("XMLns: ns1 = 'http://ejse.com/weatherservice/'); / / -------------------------------------------------------------------------------------------- ------------ // Todo: Move To Resource File Static const tchar * const g_lpszoutputmsg = _T ("Weather Information - Last Updated% S / N / N" "/ TLOCATION:% s (% s) / n / tTempRature:% s / n / tForecast:% s / n / t" "Visibility:% S / N / Thumidity:% S / N / TPRESSURE:% S / N"); / / -------------------------------------------------------------------------------------------- ------------ #ENDIF / / _SERVERXMLHTTP1_H_THE SOURCE CODE File (Serverxmlhttp1.cpp) #include "stdafx.h" #include "serverxmlhttp1.h" // utility functionvoid getxpathexprvalue (ccomqiptr LPCTSTR LPSZXPATHEXPR, LPSTR LPSZRESULTVALUE) { Uses_Conversion; CComptr SpResultNode = spresponsexmldoc-> selectsinglenode (_BSTR_T (LPSZXPATHEXPR); IF (SpResultNode.p! = null) _TCSCPY (LPSZRESULTVALUE, W2A (_BSTR_T (SpResultNode-> NodetyPedValue)))); } / / -------------------------------------------------------------------------------------------- ------------------------------ // Function Uses Serverxmlhttp to send a get / post / soap request to a .NET Web Services, // and then uses msxml dom to process the response xml text. // // illustrates calling a .NET Web Service Either by Sending A get Request, // OR a http post or by using the soap method. // // iMethod Parameter: // 0: (Default) http Get // 1: http post // 2: SOAP / / -------------------------------------------------------------------------------------------- ------------------------------ Void CallwebService (LPCTSTSTSZZIPCODE, INT IMETHOD = 0) { Float fTemprature = -999; Uses_Conversion; // Create An Instance of ServerXMLHTTP Class CComptr HRESULT HR = SPSERVERXMLHTTP1.COCREATEINSTANCE (CLSID_SERVERXMLHTTP40); Check_hr (hr); Tchar Szgeturl [MAX_PATH * 2] = {0}; Tchar SzPostValue [MAX_PATH * 2] = {0}; TCHAR SZSOAPREQ [MAX_PATH * 2] = {0}; INT ipostdatalen = 0; TCHAR SZDATALEN [10] = {0}; Switch (IMETHOD) { Case 0: // http get Sprintf (szgeturl, g_lpszgeturl, szzcode); // Initialize The Synchronous Http Get Request HR = spserverxmlhttp1-> open (_bstr_t (_t ("get"), szgeturl, variant_false; Check_hr (hr); // send the http get request HR = spserverxmlhttp1-> send (); CHECK_HR (HR); Break; Case 1: // HTTP POST _TCSCPY (SzPostValue, _T ("zipcode ="); _TCSCAT (SZPostValue, Szzcode); ipostdatalen = _tcslen (szpostvalue); ITOA (IPostDatalen, Szdatalen, 10); // Initialize The Synchronous Http Get Request HR = spserverxmlhttp1-> open (_bstr_t (_t ("post"), g_lpszposturl, variant_false); Check_hr (hr); SpServerxmlhttp1-> setRequestHeader (_T ("content-type"), _T ("Application / X-WWW-FORM-URLENCODED")); SpServerxmlhttp1-> setquestheader (_T ("Content-length"), SZDATALEN; // send the http post request, Along with the soap request envelope text HR = spserverxmlhttp1-> send (szpostvalue); Check_hr (hr); Break; Case 2: // SOAP Sprintf (SzsoapReq, G_LpszsoapReq, Szzcode); HR = spserverxmlhttp1-> open (_bstr_t (_T ("post"), g_lpszsoapendpointURL, variant_false); Check_hr (hr); // set the required soapaction and content-type headers HR = spserverxmlhttp1-> setquestheader (_T ("soapaction"), g_lpszsoapaction; Check_hr (hr); HR = spserverxmlhttp1-> setRequestHeader (_BSTR_T (_t ("content-type"), _BSTR_T (_t ("text / xml"))))))) Check_hr (hr); // send the post request, along with the soap request envelope text HR = spserverxmlhttp1-> send (_BSTR_T (SzsoapReq)); Check_hr (hr); Break; } IF (200 == SPSERVERXMLHTTP1-> status) // SUCCESS { // USING MSXML DOM to Process The Response XML Text CCOMQIPTR SpResponsexmldoc = spserverxmlhttp1-> responsexml; SpResponsexmldoc-> setProperty (_bstr_t (_t ("selectnamespaces"), g_lpszxpathselns; Tchar Szlastupdated [MAX_PATH] = {0}; Tchar Szlocation [MAX_PATH] = {0}; tchar szreportedat [max_path] = {0}; Tchar Sztemprature [MAX_PATH] = {0}; Tchar Szforecast [MAX_PATH] = {0}; TCHAR SZVISIBILITY [MAX_PATH] = {0}; Tchar Szhumidity [MAX_PATH] = {0}; Tchar Szpressure [MAX_PATH] = {0}; GetxPatHexPrvalue (spresponsexmldoc, _t ("// ns1: lastupdated"), szlastupdated; GetxPatHexPrvalue (spresponsexmldoc, _t ("// ns1: location"), szlocation GetxPatHexPrvalue (spresponsexmldoc, _t ("// ns1: reportedat"), szreportedat; GetxPatHexPrvalue (SpResponsexmldoc, _T ("// ns1: temprature), sztemprate); GetxPatHexPrvalue (spresponsexmldoc, _t ("// ns1: forecast"), SZFORECAST); GetxPatHexPrvalue (SpResponsexmldoc, _T ("// ns1: visibility"), szvisibility); GetxPatHexPrvalue (SpResponsexmldoc, _T ("// ns1: humidity"), SZHumidity GetxPatHexPrvalue (Spresponsexmldoc, _T ("// ns1: press"), SZPRESSURE); Printf (g_lpszoutputmsg, szlastupdated, szreportedat, szlocation, Sztemprature, Szforecast, Szvisibility, Szhumidity, Szpressure; } Else { Printf (_t ("/ Nerror:% S / N"), W2A (SpServerxmlhttp1-> statustext); } } // main, the entry point function Int main (int Argc, char * argv []) { IF (Argc <2) {// insufficient parameters Printf (_t ("/ Nserverxmlhttp1.exe: sample web service client to get" "THE Weather Information for a Valid Given U.S. Zipcode / N")))) Printf (_t ("/ nusage: /tserverxmlhttp1.exe "EXamples: /n/tserverxmlhttp1.exe 98007 / n / t" "Serverxmlhttp1.exe 98007 1")); Printf (_t ("/ n / npress enter to contact ...)); GetChar (); Return -1; } Try { HRESULT HR = Coinitialize (NULL); Check_hr (HR); // the method (get [0] / post [1] / soap [2]) INT iCallMethod = 0; IF (Argc> = 3 && Argv [2]! = null) iCallMethod = ATOI (Argv [2]); CallWebService ((LPCTSTR) Argv [1], ICALLMETHOD); } Catch (int) { // Todo: Error Handling Printf (_T ("exception raised!"); } Couninitialize (); Printf (_t ("/ n / npress enter to contact ...)); GetChar (); Return 0; } Output: The above sample application uses MSXML ServerXMLHTTP component to call a XML Web Service either by sending a HTTP GET, HTTP POST or a SOAP request The iMethod parameter to the CallWebService supporting function decides which method to use while invoking the Web Service.. The header file imports the MSXML type library, and declares few strings used for sending the Web Service request and to process the response XML. The CPP source code file, first creates an instance of ServerXMLHTTP class, and then based on iMethod parameter, the switch statement sends the HTTP GET, POST, or SOAP request, and if the request was successful (HTTP status code = 200), responseXML DOM object and XPath expressions are used to get the returned weather information. 3. Using Microsoft SOAP Toolkit 3.0 (High -LEVEL API) The Microsoft SOAP Toolkit Is A Set of Com Components Used TO: invoke Web Services on the client-side, map Web Service method calls to the COM object methods, and to marshal and unmarshal (that is to create, transmit, read and process) SOAP messagesIn this article we'll keep the focus on invoking the Web Services using this toolkit The SOAP toolkit offers high-level API and low-level API As the names suggest, the high-level API hides the SOAP-messaging related details and you feel like you are calling a COM object;.. whereas, with the low-level API, you exactly know how the SOAP request and response messages will look like. To download the SOAP Toolkit and for more information on this, visit msdn.microsoft.com/soap. The following sample application uses the Microsoft SOAP Toolkit version 3.0 high-level API to invoke Domain name Checker Web Service to see if the specified domain name is availabe or not. Note that the SOAP Tookit has the dependancy on the MSXML, and hence the following header file imports MSXML typelib in addition to The soap toolki T Type Library. The header file (soaptoolkit1.h): # iFNDef _soaptoolkit1_h_ # define _soaptoolkit1_h_ #include "atlbase.h" #import USING NAMESPACE MSXML2; #import "c: / program files / common files / mssoap / binaries / mssoap30.dll" named_guids / Exclude ("iStream", "IrrorInfo", "ISEQUENTIALSTREAM", "_large_integer", / / "_Ularge_integer", "tagstatstg", "_filetime") Using Namespace MSSOAPLIB30; #define check_hr (hr) {if (failed (hr)) {throw -1;}} / / -------------------------------------------------------------------------------------------- ----------------------- Static const tchar * const g_lpszwsdl_url = _T ("http://services.xmethods.net/soap/urn: xmethods-domainchecker.wsdl); / / -------------------------------------------------------------------------------------------- ----------------------- # Endif //_soaptoolkit1_h_ The source code file (SOAPTOOLKIT1.CP) #include "stdafx.h" #include "soaptoolkit1.h" Void CallwebService (_BSTR_T BSTRDOMAINNAME) { Uses_Conversion; CComptr HRESULT HR = SPSOAPCLIENT.COCREATEINSTANCE (CLSID_SOAPCLIENT 30); Check_hr (hr); HR = SPSOAPCLIENT-> MSSOAPinit (_BSTR_T (g_lpszwsdl_url), L "", l ", l" "); Check_hr (hr); // Call The Web Service Method Wchar * pwcmethodname = l "checkdomain"; Dispid Dispidfn = 0; HR = SPSOAPCLIENT-> GetIDSOFNAMES (IID_NULL, & PWCMETHODNAME, 1, Locale_system_default, & dispidfn; Check_hr (hr); UNSIGNED INT UARGERR; Variant varg [1]; VARG [0] .vt = vt_bstr; VARG [0] .BStrval = BSTRDOMAINNAME; Dispparams params; Params.cargs = 1; Params.rgvarg = varg; Params.cnamedargs = 0; Params.rgdispidnamedargs = null; _VARIANT_T RESULT; UARGERR = -1; EXCEPINFO EXCEPINFO; MEMSET (& Excepinfo, 0, Sizeof (Excepinfo); HR = SPSOAPCLIENT-> Invoke (Dispidfn, IID_NULL, LOCALE_SYSTEM_DEFAULT, Dispatch_method, & params, & Result, & Excepinfo, & UARGERR Check_hr (hr); IF (Result.VT = VT_BSTR) { Printf ("Domain% s."), W2A (BSTRDOMAINNAME), W2A (Result.Bstrval); Printf (_t ("/ n / npress enter to contact ...)); GetChar (); } } Int main (int Argc, char * argv []) { IF (Argc <2) {// insufficient parameters Printf (_t ("/ nsoaptoolkit1.exe: sample Web service client to check" "WHETHER A DOMAIN Name IS Available or Not / N"))) Printf (_t ("/ nusage: /tsoaptoolkit1.exe "Soaptoolkit1.exe mywebsiteurl.com"))); Printf (_t ("/ n / npress enter to contact ...)); GetChar (); Return -1; } Try { HRESULT HR = Coinitialize (NULL); Check_hr (hr); Callwebservice (_BSTR_T (Argv [1])); } Catch (int) { // Todo: Error Handling Printf (_T ("exception raised!"); } Couninitialize (); Return 0; } Output:. The header file imports MSXML and SOAP Toolkit type libraries, and declares the Web Service WSDL URL string The SoapClient30 class is used to invoke the Web Services and this class is the basis of the SOAP toolkit high-level API The CPP. source code file above creates an instance of SoapClient30 class, followed by calling MSSoapInit member function, passing it the WSDL URL. The MSSoapInit member function is used to initialize the SoapClient30 object using the WSDL file, and once we do this, the SoapClient30 instance can be used to call the Web Service method, like any other COM object that implements IDispatch interface. Once the SoapClient30 object is initialized using the WSDL file, IDispatch methods (GetIDsOfNames and Invoke) can be called on this object for any of the Web Service method The Above Code Illustrates this for the checkdomain Web Service Method. 4. Using Microsoft SOAP Toolkit 3.0 (Low-Level API) The Soap Toolkit Low-Level API Provides The Absolute Control OV Er The Soap Message Serialization and Transport. The SoapSerializer30 Class Is Used to Create The Soap Message. AS in this Example, WE ' ll be calling a Web Service over HTTP, we use the HttpConnector30 class instance to send the SOAP request message and receive the SOAP response message, over HTTP. And finally, the SoapReader30 class is used to read the SOAP response message. The SoapReader30 class offers various methods and properties to easily read / parse / extract the information from the SOAP message. The following sample application uses Microsoft SOAP Toolkit 3.0 low-level API classes to invoke the SearchMusicTeachers Web Service, to find out the music teachers details in the given US zip code. Only Zip code value is accepted as the command line parameter, other values (such as instrument, result count restriction, radius, skill level, etc.) are hard-coded in this sample application. The source code file (SOAPToolkitLowLevel. CPP): # include "stdafx.h" #include #include "atlbase.h" #import USING NAMESPACE MSXML2; #import "C: / Program files / compon files / mssoap / binaries / mssoap30.dll" / Exclude ("iStream", "IrrorInfo", "ISEQUENTIALSTREAM", "_large_integer", / / "_Ularge_integer", "tagstatstg", "_filetime") Using Namespace MSSOAPLIB30; Void CallwebService (_BSTR_T ZIPCODE) { Isoapserializerptr serializer; IsoapReaderptr Reader; IsoapConnectorptr Connector; HRESULT HR = S_OK; HR = connector.createInstance (__ uuidof (httpconnector30)); Connector-> Property [_T ("endpointurl")] = _T ("http://www.perfectxml.net/webservices/musicteachers/musicteachers.asmx?wsdl"); HR = connector-> connect (); Connector-> Property [_T ("soapaction")] = _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/findmusicteachers"); hr = connector-> beginMessage (); HR = serializer.createInstance (__ uuidof (soapserializer30); HR = serializer-> init (_variant_t ((iunknown *) connectionor-> inputstream)); HR = Serializer-> Startenvelope (_T ("soap"), _ t ("none"), _ t ("")); HR = Serializer-> StartBody (_t (")); HR = Serializer-> StartElement (_T ("FindMusicTeachers", _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/"), _T ("none"), _ t ("")); HR = Serializer-> StartElement (_T ("zipcode"), _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/"), _T ("none"), _ t ("")); HR = serializer-> WritestRing (zipcode); HR = serializer-> endelement (); HR = Serializer-> StartElement (_t ("inStrument"), _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/"), _T ("none"), _ t ("")); HR = serializer-> WritestRing (_T ("0")); HR = serializer-> endelement (); HR = Serializer-> StartElement (_T ("Skilllevel"), _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/"), _T ("none"), _ t ("")); HR = serializer-> WritestRing (_t ("0")); HR = serializer-> endelement (); HR = serializer-> startElement (_t ("style"), _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/"), _T ("none"), _ t ("")); HR = serializer-> WritestRing (_t ("0")); HR = serializer-> endelement (); HR = serializer-> StartElement (_t ("radius"), _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/"), _ T ("none"), _ t ("")); HR = serializer-> WriteString (_T ("10")); HR = serializer-> endelement (); HR = Serializer-> StartElement (_T ("RestrictResultscount"), _T ("http://www.perfectxml.com/netwebsvcs/musicteachers/"), _T ("none"), _ t ("")); HR = Serializer-> WritestRing (_T ("5")); HR = serializer-> endelement (); HR = serializer-> endelement (); HR = serializer-> endbody (); HR = serializer-> EndENVelope (); HR = connector-> endmessage (); HR = reader.createInstance (__ uuidof (soapreader30)); HR = Reader-> Load (_VARIANT_T ((iunknown *) connector-> outputstream), _t (")); CCOMQIPTR Spreesponsexmldom = Reader-> DOM; // Todo: Process The Response SOAP XML AND DISPLAY THE RESULTS // for now, Just Printing The Response XML Text AS IT IS. Uses_Conversion; Printf (_T ("Response:% S / N"), (const char *) W2a (spresponsexmldom-> xml); Printf (_t ("/ n / npress enter to contact ...)); GetChar (); } Int main (int Argc, char * argv []) { Coinitialize (NULL); IF (Argc <2) {// insufficient parameters Printf (_t ("/ nsoaptoolkitlowlevel.exe: sample web service client to find out "Music Teachers With 10-Mile Radius of a Valid Given U.S. Zipcode / N")) Printf (_t ("/ nusage: /tsoaptoolkitlowlevel.exe "EXamples: /n/tsoaptoolkitlowlevel.exe 98007 / n / t" "SOAPTOOLKITLOWLVEL.EXE 60195")))) Printf (_t ("/ n / npress enter to contact ...)); GetChar (); Return -1; } Callwebservice (_BSTR_T (Argv [1])); Couninitialize (); return 0;} Output:.. We do not make use of the header file in this sample application The sample source code CPP file above, imports the MSXML and SOAP Toolkit type libraries The supporting function CallWebService (which is called from the main function) , creates instances of SoapSerializer, HttpConnector, and SoapReader classes. The HttpConnector instance is initialized by setting the endPointURL and the SoapAction properties, and the Connect method is used to initialize the HttpConnector instance by using the WSDL. Note how the SoapSerializer class is used to precisely create the SOAP request message. This class provides the full control over how the message should look like, by allowing us to specify the namespace value, namespaces prefixes to use, encoding style, and other structural details of the SOAP envelope. The SoapSerializer Init Method is used Above to associate the request envelope with the transport input .hen the soap request envelope is flully created using the so apSerializer members, the HttpConnector EndMessage method is called to indicate that the request envelope is ready, and to actually post the SOAP message and receive the response, synchronously. The HttpConnector OutputStream is used to load the response message into the the SoapReader object. In this particular example, we just access the Dom property on the Reader, to load the response SOAP envelope into a MSXML DOMDocument object. You may parse and process this DOMDocument object to get the individual result values. For brevity, we just print the response XML text AS IT IS in The Above Example. 5. USING POCKETSOAP V1.4.1 Pocketsoap Is A Com Component That Can Be Used To Invoke Web Services. The Following Sample C application uses PocketSOAP v1.4.1 COM component to invoke SalesRankNPrice sample Web Service, to find out the Amazon.com sales rank and the price for any given ISBN value The source code file (PocketSOAP1.cpp):. # include "stdafx.h" #include "atlbase.h" #import "c: / program files / simonfell / pocketsoap / psoap32.dll" named_guids Using namespace pocketsoap; Void CallwebService (_BSTR_T BSTRISBN) { CComptr HRESULT HR = SpenVelope.coCreateInstance (CLSID_COENVELOPE); SpenVelope-> setMethod (_T ("getamazonsalesranknprice), _T ("http://www.perfectxml.com/netwebsvcs/bookservice")); SpenVelope-> parameters-> Create (_t ("isbn"), Bstrisbn, _T ("http://www.perfectxml.com/books/bookservice"), _T (""), _t (")); CComptr HR = SPHTTPTRANSPORT.COCREATEINSTANCE (CLSID_HTTTRANSPORT); SphttpTransport-> soapaction = L "http://www.perfectxml.com/netwebsvcs/bookservice/getamazonsalesranknprice"; _BSTR_T BSTRENVELOPE = SPENVELOPE-> Serialize (); HR = SPHTTPTRANSPORT-> Send _T ("http://www.perfectxml.net/webservices/salesranknprice/bookservice.asmx"), Bstrenvelope); Ccomvariant Cvtransport (SPHTTTRANSPORT); Spenvelope-> Parse (CVTransport, _T (")); Bstrenvelope = SpenVelope-> Serialize (); Uses_Conversion; Printf (_T ("response: / n% s"), W2a (bstrenvelope); Printf (_t ("/ n / npress enter to contact ...)); GetChar (); } Int main (int Argc, char * argv []) { IF (Argc <2) {// insufficient parameters Printf (_t ("/ npocketsoap1.exe: sample web service client to find out "Amazon.com sales rank and price for a given isbn./n") ;printf(_t("/nusage :/tpocketsoap1.exe "EXamples: /n/tpocketsoap1.exe 1861005318 / N / t" "Pocketsoap1.exe 0735712867")); Printf (_t ("/ n / npress enter to contact ...)); GetChar (); Return -1; } HRESULT HR = Coinitialize (NULL); Callwebservice (_BSTR_T (Argv [1])); Couninitialize (); Return 0; } Output: The above C code begins by importing the PocketSOAP type library, and then includes the supporting function CallWebService definition This function uses the ISOAPEnvelope interface methods to initialize the SOAP request message (by defining the Web Service method to call, namespace to use. , and defining the parameters). Next, it uses the IHTTPTransportAdv interface methods to set the SOAPAction, and to actually post the SOAP request. The resultant message is parsed and loaded into the ISOAPEnvelope object, which is then serialized as a string and written out to the console SummaryThe goal of this article was to show you some of the ways in which you can build Web Services client applications, specifically using Visual C The first example illustrated using MSXML XMLHTTP for this purpose;.. next application used ServerXMLHTTP to invoke a Web service; third sample application used Microsoft Soap Toolkit High-Level API, While The Fourth Application Presented The Code That Used Microsoft SOAP Toolkit Low-Level API. Final, And Fifth Application, Illustrate Using Pocketsoap CORRARY to CALL A Web Service Method. Download: cppsoap.zip (353 KB Zip file) Related Links: PerfectXML MSXML Focus Section Visual Basic Developer's Guide to SOAP Microsoft & Web Services (SOAP) SOAP Toolkit 3.0 C Web services client using Systinet WASP Server for C Simplified SOAP Development with SOAP :: Lite - Part IAbout the author: Darshan Singh is the founder of PerfectXML.com, the XML community Web site. As an author, he has co-authored various books published by Wrox Press and has various articles for PerfectXML.com, and other technical sites such as ASPToday and MSDN. Darshan can be reached at written Darshan@perfectXml.com. script> GET OUR Newsletter: E-mail address: Recent Newsletter Discount Subscription Offer 10% Discount Two Free Issues of Web Services Journal 10% Discount Two Free Issues of XML-JOURNAL Featured vendors Perfectxml.com is a proud Winner of Best Educational Web Site (Finalist)