POST /hvlrsms/webservice/gisu.asmx HTTP/1.1
Host: 192.168.1.22
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/HelloWorld"
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<HelloWorld xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<HelloWorldResponse xmlns="http://tempuri.org/">
<HelloWorldResult>string</HelloWorldResult>
</HelloWorldResponse>
</soap:Body>
</soap:Envelope>
/*
* ============================================================================
* Name : CClientEngine of ClientEngine.h
* Part of : HTTP Client Example
* Created : 06/26/2006 by Forum Nokia
* Version : 2.0
* Copyright: Forum Nokia
* ============================================================================
*/
#ifndef __CLIENTENGINE_H__
#define __CLIENTENGINE_H__
#include <coecntrl.h>
#include <http\mhttpdatasupplier.h>
#include <http\mhttptransactioncallback.h>
#include <http\mhttpauthenticationcallback.h>
#include <es_sock.h>
/*
* Forward declarations
*/
class RHTTPSession;
class RHTTPTransaction;
/*
* MClientObserver
* CClientEngine passes events and responses body data with this interface.
* An instance of this class must be provided for construction of CClientEngine.
*/
class MClientObserver
{
public:
virtual void ClientEvent(const TDesC& aEventDescription) = 0;
virtual void ClientBodyReceived(const TDesC8& aBodyData) = 0;
};
/*
* Provides simple interface to HTTP Client API.
*/
class CClientEngine : public CBase,
public MHTTPTransactionCallback,
public MHTTPDataSupplier
// public MHTTPAuthenticationCallback
{
public:
static CClientEngine* NewL(MClientObserver& iObserver);
static CClientEngine* NewLC(MClientObserver& iObserver);
~CClientEngine();
void IssueHTTPGetL(const TDesC8& aUri);
void IssueHTTPPostL(const TDesC8& aUri,const TDesC8& aBody);
void CancelTransaction();
inline TBool IsRunning() { return iRunning; };
private:
void ConstructL();
CClientEngine(MClientObserver& iObserver);
void SetHeaderL(RHTTPHeaders aHeaders, TInt aHdrField,
const TDesC8& aHdrValue);
void SetHeaderL(RHTTPHeaders aHeaders, const TDesC8 &aHeaderField, const TDesC8 &aHeaderValue);
/*
* From MHTTPSessionEventCallback
*/
private:
void MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
TInt MHFRunError( TInt aError, RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
/*
* From MHTTPDataSupplier (needed for HTTP POST)
*/
private:
void ReleaseData();
TBool GetNextDataPart(TPtrC8& aDataPart);
TInt Reset();
TInt OverallDataSize();
void SetupConnectionL();
/*
* From MHTTPAuthenticationCallback (needed for HTTP authentication)
*/
//private:
private:
// declare members
RSocketServ iSocketServ;
RConnection iConnection;
RHTTPSession iSession;
RHTTPTransaction iTransaction;
MClientObserver& iObserver; // Used for passing body data and
// events to UI.
HBufC8* iPostData; // Data for HTTP POST
TBool iRunning; // ETrue, if transaction running
TBool iConnectionSetupDone;
};
#endif // __CLIENTENGINE_H__
/*
* ============================================================================
* Name : CClientEngine of ClientEngine.cpp
* Part of : HTTP Client Example
* Created : 06/20/2006 by Forum Nokia
* Version : 2.0
* Copyright: Forum Nokia
* ============================================================================
*/
#include <avkon.hrh>
#include <aknnotewrappers.h>
#include <uri8.h>
#include <http.h>
#include <chttpformencoder.h>
#include <HttpStringConstants.h>
#include <http\RHTTPTransaction.h>
#include <http\RHTTPSession.h>
#include <http\RHTTPHeaders.h>
#include <HTTPClientExample.rsg>
#include <COMMDB.H> //Communications database
#include <CDBPREFTABLE.H> //Connection Preferences table
#include <CommDbConnPref.h>
//#include "Client.pan"
//#include "Client.hrh"
#include "ClientEngine.h"
// Used user agent for requests
_LIT8(KUserAgent, "SimpleClient 1.0");
// This client accepts all content types.
// (change to e.g. "text/plain" for plain text only)
_LIT8(KAccept, "*/*");
const TInt KStatustextBufferSize = 32;
const TInt KInfotextBufferSize = 64;
const TInt KURIBufferSize = 128;
const TInt KDefaultBufferSize = 256;
_LIT8(KPostContentType, "text/xml"); // Content type sent in a POST request
_LIT8(KSoapAction, "SOAPAction");
_LIT8(KSoapActionParam, "http://tempuri.org/HelloWorld");
_LIT8(KHostParam, "192.168.1.22");
_LIT8(KCharsetParam, "utf-8");
// ----------------------------------------------------------------------------
// CClientEngine::NewL()
//
// Creates instance of CClientEngine.
// ----------------------------------------------------------------------------
CClientEngine* CClientEngine::NewL(MClientObserver& aObserver)
{
CClientEngine* self = CClientEngine::NewLC(aObserver);
CleanupStack::Pop(self);
return self;
}
// ----------------------------------------------------------------------------
// CClientEngine::NewLC()
//
// Creates instance of CClientEngine.
// ----------------------------------------------------------------------------
CClientEngine* CClientEngine::NewLC(MClientObserver& aObserver)
{
CClientEngine* self = new (ELeave) CClientEngine(aObserver);
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
// ----------------------------------------------------------------------------
// CClientEngine::CClientEngine()
//
// First phase constructor.
// ----------------------------------------------------------------------------
CClientEngine::CClientEngine(MClientObserver& aObserver)
: iObserver(aObserver),
iPostData(NULL),
iRunning(EFalse)
{
}
// ----------------------------------------------------------------------------
// CClientEngine::~CClientEngine()
//
// Destructor.
// ----------------------------------------------------------------------------
CClientEngine::~CClientEngine()
{
iSession.Close();
// and finally close handles
iConnection.Close();
iSocketServ.Close();
delete iPostData;
}
// ----------------------------------------------------------------------------
// CClientEngine::ConstructL()
//
// Second phase construction.
// ----------------------------------------------------------------------------
void CClientEngine::ConstructL()
{
// Open RHTTPSession with default protocol ("HTTP/TCP")
TRAPD(err, iSession.OpenL());
if(err != KErrNone)
{
// Most common error; no access point configured, and session creation
// leaves with KErrNotFound.
_LIT(KErrMsg,
"Cannot create session. Is internet access point configured?");
_LIT(KExitingApp, "Exiting app.");
CEikonEnv::Static()->InfoWinL(KErrMsg, KExitingApp);
User::Leave(err);
}
}
// ----------------------------------------------------------------------------
// CClientEngine::SetHeaderL()
//
// Used to set header value to HTTP request
// ----------------------------------------------------------------------------
void CClientEngine::SetHeaderL(RHTTPHeaders aHeaders,
TInt aHdrField,
const TDesC8& aHdrValue)
{
RStringF valStr = iSession.StringPool().OpenFStringL(aHdrValue);
CleanupClosePushL(valStr);
THTTPHdrVal val(valStr);
aHeaders.SetFieldL(iSession.StringPool().StringF(aHdrField,
RHTTPSession::GetTable()), val);
CleanupStack::PopAndDestroy(); // valStr
}
void CClientEngine::SetHeaderL(RHTTPHeaders aHeaders, const TDesC8 &aHeaderField, const TDesC8 &aHeaderValue)
{
RStringF valStr = iSession.StringPool().OpenFStringL(aHeaderValue);
CleanupClosePushL(valStr);
THTTPHdrVal headerVal(valStr);
RStringF sHeaderField = iSession.StringPool().OpenFStringL(aHeaderField);
CleanupClosePushL(sHeaderField);
aHeaders.SetFieldL(sHeaderField, headerVal);
CleanupStack::PopAndDestroy(2); // valStr
}
// ----------------------------------------------------------------------------
// CClientEngine::IssueHTTPGetL()
//
// Start a new HTTP GET transaction.
// ----------------------------------------------------------------------------
void CClientEngine::IssueHTTPGetL(const TDesC8& aUri)
{
SetupConnectionL();
// Parse string to URI (as defined in RFC2396)
TUriParser8 uri;
uri.Parse(aUri);
// Get request method string for HTTP GET
RStringF method = iSession.StringPool().StringF(HTTP::EGET,RHTTPSession::GetTable());
// Open transaction with previous method and parsed uri. This class will
// receive transaction events in MHFRunL and MHFRunError.
iTransaction = iSession.OpenTransactionL(uri, *this, method);
// Set headers for request; user agent and accepted content type
RHTTPHeaders hdr = iTransaction.Request().GetHeaderCollection();
SetHeaderL(hdr, HTTP::EUserAgent, KUserAgent);
SetHeaderL(hdr, HTTP::EAccept, KAccept);
// Submit the transaction. After this the framework will give transaction
// events via MHFRunL and MHFRunError.
iTransaction.SubmitL();
iRunning = ETrue;
}
// ----------------------------------------------------------------------------
// CClientEngine::IssueHTTPPostL()
//
// Start a new HTTP POST transaction.
// ----------------------------------------------------------------------------
void CClientEngine::IssueHTTPPostL(const TDesC8& aUri,
const TDesC8& aBody)
{
SetupConnectionL();
// Parse string to URI
TUriParser8 uri;
uri.Parse(aUri);
// Copy data to be posted into member variable; iPostData is used later in
// methods inherited from MHTTPDataSupplier.
delete iPostData;
iPostData = aBody.AllocL();
// Get request method string for HTTP POST
RStringF method = iSession.StringPool().StringF(HTTP::EPOST,RHTTPSession::GetTable());
// Open transaction with previous method and parsed uri. This class will
// receive transaction events in MHFRunL and MHFRunError.
iTransaction = iSession.OpenTransactionL(uri, *this, method);
// Set headers for request; user agent, accepted content type and body's
// content type.
RHTTPHeaders hdr = iTransaction.Request().GetHeaderCollection();
TBuf8<64> buf;
buf.Zero();
buf.AppendNum(iPostData->Length());
SetHeaderL(hdr, HTTP::EHost, KHostParam);
SetHeaderL(hdr, HTTP::EContentType, KPostContentType);
SetHeaderL(hdr, HTTP::ECharset, KCharsetParam);
SetHeaderL(hdr, HTTP::EContentLength, buf);
SetHeaderL(hdr,KSoapAction,KSoapActionParam);
// Set this class as an data supplier. Inherited MHTTPDataSupplier methods
// are called when framework needs to send body data.
MHTTPDataSupplier* dataSupplier = this;
iTransaction.Request().SetBody(*dataSupplier);
// Submit the transaction. After this the framework will give transaction
// events via MHFRunL and MHFRunError.
iTransaction.SubmitL();
iRunning = ETrue;
}
// ----------------------------------------------------------------------------
// CClientEngine::CancelTransaction()
//
// Cancels currently running transaction and frees resources related to it.
// ----------------------------------------------------------------------------
void CClientEngine::CancelTransaction()
{
if(!iRunning)
return;
// Close() also cancels transaction (Cancel() can also be used but
// resources allocated by transaction must be still freed with Close())
iTransaction.Close();
// Not running anymore
iRunning = EFalse;
_LIT(KTransactionCancelled, "Transaction cancelled");
iObserver.ClientEvent(KTransactionCancelled);
}
// ----------------------------------------------------------------------------
// CClientEngine::MHFRunL()
//
// Inherited from MHTTPTransactionCallback
// Called by framework to pass transaction events.
// ----------------------------------------------------------------------------
void CClientEngine::MHFRunL(RHTTPTransaction aTransaction,
const THTTPEvent& aEvent)
{
switch (aEvent.iStatus)
{
case THTTPEvent::EGotResponseHeaders:
{
// HTTP response headers have been received. Use
// aTransaction.Response() to get the response. However, it's not
// necessary to do anything with the response when this event occurs.
// Get HTTP status code from header (e.g. 200)
RHTTPResponse resp = aTransaction.Response();
TInt status = resp.StatusCode();
}
break;
case THTTPEvent::EGotResponseBodyData:
{
// Part (or all) of response's body data received. Use
// aTransaction.Response().Body()->GetNextDataPart() to get the actual
// body data.
// Get the body data supplier
MHTTPDataSupplier* body = aTransaction.Response().Body();
TPtrC8 dataChunk;
// GetNextDataPart() returns ETrue, if the received part is the last
// one.
TBool isLast = body->GetNextDataPart(dataChunk);
iObserver.ClientBodyReceived(dataChunk);
body->ReleaseData();
}
break;
case THTTPEvent::EResponseComplete:
{
// Indicates that header & body of response is completely received.
// No further action here needed.
}
break;
case THTTPEvent::ESucceeded:
{
// Indicates that transaction succeeded.
// Transaction can be closed now. It's not needed anymore.
aTransaction.Close();
iRunning = EFalse;
}
break;
case THTTPEvent::EFailed:
{
// Transaction completed with failure.
aTransaction.Close();
iRunning = EFalse;
}
break;
default:
// There are more events in THTTPEvent, but they are not usually
// needed. However, event status smaller than zero should be handled
// correctly since it's error.
{
TBuf<KInfotextBufferSize> text;
if (aEvent.iStatus < 0)
{
_LIT(KErrorStr, "Error: %d");
text.Format(KErrorStr, aEvent.iStatus);
// Just close the transaction on errors
aTransaction.Close();
iRunning = EFalse;
}
else
{
// Other events are not errors (e.g. permanent and temporary
// redirections)
_LIT(KUnrecognisedEvent, "Unrecognised event: %d");
text.Format(KUnrecognisedEvent, aEvent.iStatus);
}
iObserver.ClientEvent(text);
}
break;
}
}
// ----------------------------------------------------------------------------
// CClientEngine::MHFRunError()
//
// Inherited from MHTTPTransactionCallback
// Called by framework when *leave* occurs in handling of transaction event.
// These errors must be handled, or otherwise HTTP-CORE 6 panic is thrown.
// ----------------------------------------------------------------------------
TInt CClientEngine::MHFRunError(TInt aError,
RHTTPTransaction /*aTransaction*/,
const THTTPEvent& /*aEvent*/)
{
// Just notify about the error and return KErrNone.
TBuf<KInfotextBufferSize> text;
_LIT(KRunError, "MHFRunError: %d");
text.Format(KRunError, aError);
iObserver.ClientEvent(text);
return KErrNone;
}
// ----------------------------------------------------------------------------
// CClientEngine::GetNextDataPart()
//
// Inherited from MHTTPDataSupplier
// Called by framework when next part of the body is needed. In this
// this provides data for HTTP post.
// ----------------------------------------------------------------------------
TBool CClientEngine::GetNextDataPart(TPtrC8& aDataPart)
{
if(iPostData)
{
// Provide pointer to next chunk of data (return ETrue, if last chunk)
// Usually only one chunk is needed, but sending big file could require
// loading the file in small parts.
aDataPart.Set(iPostData->Des());
}
return ETrue;
}
// ----------------------------------------------------------------------------
// CClientEngine::ReleaseData()
//
// Inherited from MHTTPDataSupplier
// Called by framework. Allows us to release resources needed for previous
// chunk. (e.g. free buffers)
// ----------------------------------------------------------------------------
void CClientEngine::ReleaseData()
{
// It's safe to delete iPostData now.
delete iPostData;
iPostData = NULL;
}
// ----------------------------------------------------------------------------
// CClientEngine::Reset()
//
// Inherited from MHTTPDataSupplier
// Called by framework to reset the data supplier. Indicates to the data
// supplier that it should return to the first part of the data.
// In practise an error has occured while sending data, and framework needs to
// resend data.
// ----------------------------------------------------------------------------
TInt CClientEngine::Reset()
{
// Nothing needed since iPostData still exists and contains all the data.
// (If a file is used and read in small parts we should seek to beginning
// of file and provide the first chunk again in GetNextDataPart() )
return KErrNone;
}
// ----------------------------------------------------------------------------
// CClientEngine::OverallDataSize()
//
// Inherited from MHTTPDataSupplier
// Called by framework. We should return the expected size of data to be sent.
// If it's not know we can return KErrNotFound (it's allowed and does not cause
// problems, since HTTP protocol allows multipart bodys without exact content
// length in header).
// ----------------------------------------------------------------------------
TInt CClientEngine::OverallDataSize()
{
if(iPostData)
return iPostData->Length();
else
return KErrNotFound ;
}
// ----------------------------------------------------------------------------
// CClientEngine::SetupConnectionL()
//
// The method set the internet access point and connection setups.
// ----------------------------------------------------------------------------
void CClientEngine::SetupConnectionL()
{
if( iConnectionSetupDone )
return;
iConnectionSetupDone = ETrue;
//open socket server and start the connection
User::LeaveIfError(iSocketServ.Connect());
User::LeaveIfError(iConnection.Open(iSocketServ));
// open the IAP communications database
CCommsDatabase* commDB = CCommsDatabase::NewL(EDatabaseTypeIAP);
CleanupStack::PushL(commDB);
// initialize a view
CCommsDbConnectionPrefTableView* commDBView =
commDB->OpenConnectionPrefTableInRankOrderLC(ECommDbConnectionDirectionUnknown);
// go to the first record
User::LeaveIfError(commDBView->GotoFirstRecord());
// Declare a prefTableView Object.
CCommsDbConnectionPrefTableView::TCommDbIapConnectionPref pref;
// read the connection preferences
commDBView->ReadConnectionPreferenceL(pref);
TUint32 iapID = pref.iBearer.iIapId;
// pop and destroy the IAP View
CleanupStack::PopAndDestroy(commDBView);
// pop and destroy the database object
CleanupStack::PopAndDestroy(commDB);
// Now we have the iap Id. Use it to connect for the connection.
// Create a connection preference variable.
TCommDbConnPref connectPref;
// setup preferences
connectPref.SetDialogPreference(ECommDbDialogPrefDoNotPrompt);
connectPref.SetDirection(ECommDbConnectionDirectionUnknown);
connectPref.SetBearerSet(ECommDbBearerGPRS);
//Sets the CommDb ID of the IAP to use for this connection
connectPref.SetIapId(iapID);
User::LeaveIfError(iConnection.Start(connectPref));
//set the sessions connection info
RStringPool strPool = iSession.StringPool();
RHTTPConnectionInfo connInfo = iSession.ConnectionInfo();
//to use our socket server and connection
connInfo.SetPropertyL ( strPool.StringF(HTTP::EHttpSocketServ,
RHTTPSession::GetTable() ), THTTPHdrVal (iSocketServ.Handle()) );
connInfo.SetPropertyL ( strPool.StringF(HTTP::EHttpSocketConnection,
RHTTPSession::GetTable() ),
THTTPHdrVal (REINTERPRET_CAST(TInt, &(iConnection))) );
}
// end of file
#ifndef __XMLHANDLER_H__
#define __XMLHANDLER_H__
// INCLUDE FILES
#include <ecom.h>
#include <e32base.h>
#include <xml\contenthandler.h> // for MContentHandler
#include <xml\parser.h> // for CParser
#include <xml\WbxmlExtensionHandler.h>
// CLASS DECLARATION
using namespace Xml;
/**
* MXmlHandlerObserver, an observer to CXmlHandler class.
*/
class MXmlHandlerObserver
{
public:
virtual void OnParseCompleted( TInt aError ) = 0;
};
/**
* CXmlHandler, a class to parse XML file and then output log information
* to a buffer.
*/
class CXmlHandler: public CActive, MContentHandler
{
enum TState
{
EIdle,
EReadingFile
};
public: // Constructors and destructor
static CXmlHandler* NewL( MXmlHandlerObserver& aObserver );
static CXmlHandler* NewLC( MXmlHandlerObserver& aObserver );
virtual ~CXmlHandler();
public: // Public methods
void StartParsingL( const TDesC8& aBody );
void StartParsingFL( const TDesC& aFileName );
void StartParsingWithAoL( const TDesC& aFileName );
TPtr8 DisplayResult() { return iDisplayResult->Des(); }
private: // Constructors
CXmlHandler( MXmlHandlerObserver& aObserver );
void ConstructL();
private: // from CActive
void DoCancel();
void RunL();
private: // from MContentHandler
void OnStartDocumentL( const RDocumentParameters &aDocParam, TInt aErrorCode );
void OnEndDocumentL( TInt aErrorCode );
void OnStartElementL( const RTagInfo &aElement, const RAttributeArray &aAttributes, TInt aErrorCode );
void OnEndElementL( const RTagInfo &aElement, TInt aErrorCode );
void OnContentL( const TDesC8 &aBytes, TInt aErrorCode );
void OnStartPrefixMappingL( const RString &aPrefix, const RString &aUri, TInt aErrorCode );
void OnEndPrefixMappingL( const RString &aPrefix, TInt aErrorCode );
void OnIgnorableWhiteSpaceL( const TDesC8 &aBytes, TInt aErrorCode );
void OnSkippedEntityL( const RString &aName, TInt aErrorCode );
void OnProcessingInstructionL( const TDesC8 &aTarget, const TDesC8 &aData, TInt aErrorCode);
void OnError( TInt aErrorCode );
TAny *GetExtendedInterface( const TInt32 aUid );
private: // Private methods
void AppendText( const TDesC8& aText );
void AppendTag( const TDesC8& aTag, TBool aIsClosingTag );
private: // Private data
MXmlHandlerObserver& iObserver;
CParser* iParser;
HBufC8* iBuffer;
HBufC8* iDisplayResult;
TState iState;
RFile iFile;
};
#endif /* __XMLHANDLER_H__ */
// End of File
// INCLUDE FILES
#include <coemain.h>
#include <f32file.h>
#include "XmlHandler.h"
#include <aknnotewrappers.h>
// CONSTANTS
const TInt KBufferSize = 1024; // buffer size to store the result of
// XML parsing -> the actual buffer size
// can expand if needed (see AppendText())
const TInt KFileBufferSize = 1024; // buffer size for file reading
const TInt KOverheadLen = 4; // length of (KOpeningTag + KClosingTag
// + KSlash + KEndOfLine)
_LIT8(KOpeningTag, "<" );
_LIT8(KClosingTag, ">" );
_LIT8(KSlash, "/" );
_LIT8( KXmlMimeType, "text/xml" );
// --------------------------------------------------------------------------
CXmlHandler* CXmlHandler::NewL( MXmlHandlerObserver& aObserver )
{
CXmlHandler* self = CXmlHandler::NewLC( aObserver );
CleanupStack::Pop( self );
return self;
}
// --------------------------------------------------------------------------
CXmlHandler* CXmlHandler::NewLC( MXmlHandlerObserver& aObserver )
{
CXmlHandler* self = new ( ELeave ) CXmlHandler( aObserver );
CleanupStack::PushL( self );
self->ConstructL();
return self;
}
// --------------------------------------------------------------------------
CXmlHandler::~CXmlHandler()
{
Cancel();
delete iParser;
iParser = NULL;
delete iDisplayResult;
iDisplayResult = NULL;
delete iBuffer;
iBuffer = NULL;
}
// --------------------------------------------------------------------------
CXmlHandler::CXmlHandler( MXmlHandlerObserver& aObserver ):CActive( EPriorityStandard ),
iObserver( aObserver ), iParser( 0 ), iDisplayResult( 0 ), iState( EIdle )
{
CActiveScheduler::Add( this );
}
// --------------------------------------------------------------------------
void CXmlHandler::DoCancel()
{
iParser->ParseEndL();
iFile.Close();
delete iBuffer;
iBuffer = NULL;
}
// --------------------------------------------------------------------------
void CXmlHandler::RunL()
{
if ( KErrNone == iStatus.Int() )
{
// If the buffe length is zero, it means if we have reached
// the end of the file.
if ( iBuffer->Length() == 0)
{
iParser->ParseEndL();
iFile.Close();
delete iBuffer;
iBuffer = 0;
}
// Otherwise, we continue reading the next chunk of the XML file.
else
{
// Parse the next "part" of the XML document.
iParser->ParseL( *iBuffer );
// Read the next chunk of the file.
TPtr8 bufferPtr( iBuffer->Des() );
iFile.Read( bufferPtr, KFileBufferSize, iStatus );
// Don't forget to call this... :)
SetActive();
}
}
else
{
iObserver.OnParseCompleted( iStatus.Int() );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::ConstructL()
{
iParser = CParser::NewL( KXmlMimeType, *this );
iDisplayResult = HBufC8::NewL( KBufferSize );
}
// --------------------------------------------------------------------------
void CXmlHandler::StartParsingL( const TDesC8& aBody )
{
iDisplayResult->Des().Zero();
delete iBuffer;
iBuffer = 0;
iBuffer = HBufC8::NewL( aBody.Length() );
iBuffer->Des().Copy(aBody);
iParser->ParseBeginL();
iParser->ParseL( *iBuffer );
iParser->ParseEndL();
}
void CXmlHandler::StartParsingFL( const TDesC& aFileName )
{
// Read the whole content of aFileName into iBuffer.
// IMPORTANT: This example reads the whole content within
// one-shot for simplicity reason.
// In reality, you have to read it chunk by chunk
// using active object so that your application doesn't block.
RFile file;
User::LeaveIfError( file.Open( CCoeEnv::Static()->FsSession(), aFileName, EFileRead ) );
CleanupClosePushL( file );
iDisplayResult->Des().Zero();
TInt size;
User::LeaveIfError( file.Size( size ) );
delete iBuffer;
iBuffer = 0;
iBuffer = HBufC8::NewL( size );
TPtr8 bufferPtr( iBuffer->Des() );
User::LeaveIfError( file.Read( bufferPtr ) );
CleanupStack::PopAndDestroy(); // file
// Now, we have the whole file content in iBuffer.
// We are ready to parse the XML content.
iParser->ParseBeginL();
iParser->ParseL( *iBuffer );
// Since we read the whole file contents within one-shot,
// we can call ParseEndL() right after calling ParseL().
iParser->ParseEndL();
}
// --------------------------------------------------------------------------
void CXmlHandler::StartParsingWithAoL( const TDesC& aFileName )
{
// Remember to cancel any outstanding request first.
if ( IsActive() )
{
Cancel();
}
User::LeaveIfError( iFile.Open( CCoeEnv::Static()->FsSession(), aFileName, EFileRead ) );
// Create a buffer to store the file content.
// Note that this method uses active object to read the file.
// So we have to call SetActive() at the end. Then we call CParser::ParseL()
// in RunL() method.
iDisplayResult->Des().Zero();
delete iBuffer;
iBuffer = 0;
iBuffer = HBufC8::NewL( KFileBufferSize );
TPtr8 bufferPtr( iBuffer->Des() );
iFile.Read( bufferPtr, KFileBufferSize, iStatus );
SetActive();
// Tell the parser that we are about to parse a XML document.
iParser->ParseBeginL();
}
// --------------------------------------------------------------------------
void CXmlHandler::OnStartDocumentL( const RDocumentParameters& /*aDocParam*/, TInt aErrorCode )
{
_LIT8( KOnStartDocumentL, "*** OnStartDocumentL ***" );
AppendText( KOnStartDocumentL );
AppendText(_L8("\r\n"));
if ( KErrNone == aErrorCode )
{
//可以在这里解析xml头
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnEndDocumentL( TInt aErrorCode )
{
_LIT8( KOnEndDocumentL, "*** OnEndDocumentL ***" );
AppendText( KOnEndDocumentL );
AppendText(_L8("\r\n"));
if ( KErrNone == aErrorCode )
{
// Do something here if needed....
}
iObserver.OnParseCompleted( aErrorCode );
}
// --------------------------------------------------------------------------
void CXmlHandler::OnStartElementL( const RTagInfo& aElement, const RAttributeArray& aAttributes, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// If we find the start of an element, we write to the screen,
// for example: "<tag>"
if(aErrorCode == KErrNone)
{
TInt count = aAttributes.Count();
for(TInt i=0; i<count; i++)
{
TBuf8<20> name = aAttributes[i].Attribute().LocalName().DesC();
TBuf8<20> value = aAttributes[i].Value().DesC();
}
User::After(700000);
}
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnEndElementL( const RTagInfo& /*aElement*/, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// If we find the end of an element, we write it to the screen,
// for example: "</tag>"
//AppendTag( aElement.LocalName().DesC(), ETrue );
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnContentL( const TDesC8 &aBytes, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// Display aBytes on the screen.
// Before we can display it, we have to convert the content
// from TDesC8 to TDesC16.
HBufC8* buffer = HBufC8::NewLC( aBytes.Length() + 1 );
TPtr8 bufferPtr( buffer->Des() );
bufferPtr.Copy( aBytes );
bufferPtr.Trim();
AppendText( *buffer );
AppendText(_L8("\r\n"));
CleanupStack::PopAndDestroy(); // buffer
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnStartPrefixMappingL( const RString& /*aPrefix*/, const RString& /*aUri*/, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// Do something here...
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnEndPrefixMappingL( const RString& /*aPrefix*/, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// Do something here...
//AppendText(aPrefix.DesC());
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnIgnorableWhiteSpaceL( const TDesC8& /*aBytes*/, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// Do something here...
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnSkippedEntityL( const RString& /*aName*/, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// Do something here...
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnProcessingInstructionL( const TDesC8& /*aTarget*/, const TDesC8& /*aData*/, TInt aErrorCode )
{
if ( KErrNone == aErrorCode )
{
// Do something here...
}
else
{
iObserver.OnParseCompleted( aErrorCode );
}
}
// --------------------------------------------------------------------------
void CXmlHandler::OnError( TInt aErrorCode )
{
iObserver.OnParseCompleted( aErrorCode );
}
// --------------------------------------------------------------------------
TAny* CXmlHandler::GetExtendedInterface( const TInt32 /*aUid*/ )
{
return 0;
}
// --------------------------------------------------------------------------
void CXmlHandler::AppendText( const TDesC8& aText )
{
TPtr8 displayResultPtr( iDisplayResult->Des() );
TInt len = displayResultPtr.Length();
TInt MaxLen = displayResultPtr.MaxLength();
if ( len + aText.Length() > MaxLen )
{
iDisplayResult = iDisplayResult->ReAllocL( MaxLen + KBufferSize );
displayResultPtr.Set( iDisplayResult->Des() );
}
displayResultPtr.Append( aText );
}
// --------------------------------------------------------------------------
void CXmlHandler::AppendTag( const TDesC8& aTag, TBool aIsClosingTag )
{
// Instantiate buffer to display tag information.
HBufC8* buffer = HBufC8::NewLC( aTag.Length() + ( ( aIsClosingTag ) ? KOverheadLen : KOverheadLen - 1 ) );
TPtr8 bufferPtr( buffer->Des() );
// Convert tag name from TDesC8 to TDesC16.
bufferPtr.Copy( aTag );
// Add opening tag.
if ( aIsClosingTag )
{
bufferPtr.Insert( 0, KSlash );
}
bufferPtr.Insert( 0, KOpeningTag );
// Add closing tag.
bufferPtr.Append( KClosingTag );
//bufferPtr.Append( KEndOfLine );
// Add to the result text and then destroy it.
AppendText( *buffer );
AppendText(_L8("\r\n"));
CleanupStack::PopAndDestroy(); // buffer
}
// End of File
/*
============================================================================
Name : HttpSoapClientAppUi.h
Author :
Version :
Copyright : Your copyright notice
Description : Main application UI class (controller)
============================================================================
*/
#ifndef __HTTPSOAPCLIENTAPPUI_H__
#define __HTTPSOAPCLIENTAPPUI_H__
// INCLUDES
#include <aknappui.h>
// FORWARD DECLARATIONS
class CHttpSoapClientAppView;
#include "XmlHandler.h"
#include "ClientEngine.h"
class CClientEngine;
// CLASS DECLARATION
/**
* CHttpSoapClientAppUi application UI class.
* Interacts with the user through the UI and request message processing
* from the handler class
*/
class CHttpSoapClientAppUi : public CAknAppUi,public MXmlHandlerObserver,
public MClientObserver
{
public: // Constructors and destructor
void ConstructL();
CHttpSoapClientAppUi();
virtual ~CHttpSoapClientAppUi();
private: // Functions from base classes
void HandleCommandL( TInt aCommand );
void HandleStatusPaneSizeChange();
private://MXmlHandlerObserver
virtual void OnParseCompleted( TInt aError );
private://MClientObserver
virtual void ClientEvent(const TDesC& aEventDescription);
virtual void ClientBodyReceived(const TDesC8& aBodyData);
private: // Data
CHttpSoapClientAppView* iAppView;
CXmlHandler* iXmlHandler;
CClientEngine* iClient;
};
#endif // __HTTPSOAPCLIENTAPPUI_H__
// End of File
/*
============================================================================
Name : HttpSoapClientAppUi.cpp
Author :
Version :
Copyright : Your copyright notice
Description : Main application UI class (controller)
============================================================================
*/
// INCLUDE FILES
#include <avkon.hrh>
#include <aknnotewrappers.h>
#include <stringloader.h>
#include <HttpSoapClient.rsg>
#include <f32file.h>
#include <s32file.h>
#include "HttpSoapClient.pan"
#include "HttpSoapClientAppUi.h"
#include "HttpSoapClientAppView.h"
#include "HttpSoapClient.hrh"
#include "LogFile.h"
const TInt KStatusCodeLength = 10;
// ============================ MEMBER FUNCTIONS ===============================
// -----------------------------------------------------------------------------
// CHttpSoapClientAppUi::ConstructL()
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
void CHttpSoapClientAppUi::ConstructL()
{
// Initialise app UI with standard value.
BaseConstructL();
// Create view object
iAppView = CHttpSoapClientAppView::NewL( ClientRect() );
AddToStackL(iAppView);
iXmlHandler = CXmlHandler::NewL( *this );
iClient = CClientEngine::NewL(*this);
}
// -----------------------------------------------------------------------------
// CHttpSoapClientAppUi::CHttpSoapClientAppUi()
// C++ default constructor can NOT contain any code, that might leave.
// -----------------------------------------------------------------------------
//
CHttpSoapClientAppUi::CHttpSoapClientAppUi()
{
// No implementation required
}
// -----------------------------------------------------------------------------
// CHttpSoapClientAppUi::~CHttpSoapClientAppUi()
// Destructor.
// -----------------------------------------------------------------------------
//
CHttpSoapClientAppUi::~CHttpSoapClientAppUi()
{
if ( iAppView )
{
RemoveFromStack(iAppView);
delete iAppView;
iAppView = NULL;
}
if (iXmlHandler)
{
delete iXmlHandler;
iXmlHandler = NULL;
}
if (iClient)
{
delete iClient;
iClient = NULL;
}
}
// -----------------------------------------------------------------------------
// CHttpSoapClientAppUi::HandleCommandL()
// Takes care of command handling.
// -----------------------------------------------------------------------------
//
void CHttpSoapClientAppUi::HandleCommandL( TInt aCommand )
{
switch( aCommand )
{
case EEikCmdExit:
case EAknSoftkeyExit:
Exit();
break;
case EHttpSoapClientCommand1:
{
// Load a string from the resource file and display it
iClient->CancelTransaction();
iClient->IssueHTTPPostL(_L8("/hvlrsms/webservice/gisu.asmx"),_L8("<?xml version=\"1.0\" encoding=\"utf-8\"?>
<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
<soap:Body>
<HelloWorld xmlns=\"http://tempuri.org/\" />
</soap:Body>
</soap:Envelope>"));
}
break;
default:
Panic( EHttpSoapClientUi );
break;
}
}
// -----------------------------------------------------------------------------
// Called by the framework when the application status pane
// size is changed. Passes the new client rectangle to the
// AppView
// -----------------------------------------------------------------------------
//
void CHttpSoapClientAppUi::HandleStatusPaneSizeChange()
{
iAppView->SetRect( ClientRect() );
}
void CHttpSoapClientAppUi::OnParseCompleted( TInt aError )
{
if ( KErrNone == aError )
{
TPtr8 resultPtr( iXmlHandler->DisplayResult() );
CLogFile::LogToFile(_L("c:\\debug.txt"), resultPtr);
}
else
{
TBuf8<50> buffer;
buffer.Append( _L("Error: " ) );
buffer.AppendNum( aError );
buffer.Append( _L("\r\n") );
CLogFile::LogToFile(_L("c:\\debug.txt"), (TDes8&)buffer);
}
}
void CHttpSoapClientAppUi::ClientEvent(const TDesC& aEventDescription)
{
HBufC* tempBuf = HBufC::NewL(aEventDescription.Length());
CleanupStack::PushL(tempBuf);
tempBuf->Des().Copy(aEventDescription);
CAknInformationNote* note = new (ELeave) CAknInformationNote;
note->ExecuteLD(*tempBuf);
CleanupStack::PopAndDestroy(); // tempBuf
}
void CHttpSoapClientAppUi::ClientBodyReceived(const TDesC8& aBodyData)
{
HBufC8* buf8 = HBufC8::NewL(aBodyData.Length());
CleanupStack::PushL(buf8);
buf8->Des().Copy(aBodyData);
buf8->Des().TrimAll();
iXmlHandler->StartParsingL(buf8->Des());
CleanupStack::PopAndDestroy(buf8);
}
// End of File
程序退出时,不会出现panic user 42错误