📄 clientengine.cpp
字号:
/*
* ============================================================================
* 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;
// ----------------------------------------------------------------------------
// 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);
}
// Install this class as the callback for authentication requests. When
// page requires authentication the framework calls GetCredentialsL to get
// user name and password.
InstallAuthenticationL(iSession);
}
// ----------------------------------------------------------------------------
// 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
}
// ----------------------------------------------------------------------------
// 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;
_LIT(KConnecting,"Connecting...");
iObserver.ClientEvent(KConnecting);
}
// ----------------------------------------------------------------------------
// CClientEngine::IssueHTTPPostL()
//
// Start a new HTTP POST transaction.
// ----------------------------------------------------------------------------
void CClientEngine::IssueHTTPPostL(const TDesC8& aUri,
const TDesC8& aContentType,
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();
SetHeaderL(hdr, HTTP::EUserAgent, KUserAgent);
SetHeaderL(hdr, HTTP::EAccept, KAccept);
SetHeaderL(hdr, HTTP::EContentType, aContentType);
// 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;
_LIT(KConnecting,"Connecting...");
iObserver.ClientEvent(KConnecting);
}
// ----------------------------------------------------------------------------
// 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();
// Get status text (e.g. "OK")
TBuf<KStatustextBufferSize> statusText;
statusText.Copy(resp.StatusText().DesC());
TBuf<KDefaultBufferSize> text;
_LIT(KHeaderReceived, "Header received. Status: %d %S");
text.Format(KHeaderReceived, status, &statusText);
iObserver.ClientEvent(text);
}
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
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -