📄 httpengine.cpp
字号:
// System includes
#include <chttpformencoder.h> // CHTTPFormEncoder
#include <httpstringconstants.h> // HTTP string table
#include <http/rhttpheaders.h> // RHTTPHeaders
#include <apsettingshandlerui.h>
#include <COMMDB.H>
#include <CommDbConnPref.h>
#include"HttpEngine.h"
#include "QiQiWeather.hrh"
// HTTP header values
_LIT8(KUserAgent, "QiQiWeather (1.0)"); // Name of this client app
_LIT8(KAccept, "text/*"); // Accept any (but only) text content
// ================= MEMBER FUNCTIONS =======================
CQiQiHTTPEngine* CQiQiHTTPEngine::NewL(MHTTPEngineObserver& aObserver)
{
CQiQiHTTPEngine* self = new (ELeave) CQiQiHTTPEngine(aObserver);
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(self);
return self;
}
CQiQiHTTPEngine::CQiQiHTTPEngine(MHTTPEngineObserver& aObserver)
: iActive(aObserver)
{
}
void CQiQiHTTPEngine::ConstructL()
{
// 打开RHTTPSession
iSession.OpenL();
// initialize handles
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(ECommDbConnectionDirectionOutgoing);
// 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(ECommDbConnectionDirectionOutgoing);
connectPref.SetBearerSet(ECommDbBearerGPRS);
connectPref.SetIapId(iapID);
User::LeaveIfError(iConnection.Start(connectPref));
// set them for use with open http session represented by iSession
RStringPool strP = iSession.StringPool();
RHTTPConnectionInfo connInfo = iSession.ConnectionInfo();
connInfo.SetPropertyL (strP.StringF(HTTP::EHttpSocketServ, RHTTPSession::GetTable()),
THTTPHdrVal (iSocketServ.Handle()));
TInt connPtr = REINTERPRET_CAST(TInt, &(iConnection));
connInfo.SetPropertyL (strP.StringF(HTTP::EHttpSocketConnection, RHTTPSession::GetTable()),
THTTPHdrVal (connPtr));
}
CQiQiHTTPEngine::~CQiQiHTTPEngine()
{
// Close session
iSession.Close(); // Will also close any open transactions
iConnection.Close();
iSocketServ.Close();
if (iUri)
{
delete iUri;
iUri = NULL;
}
}
/**
* Override of pure virtual method in MHTTPTransactionCallback.
* Called to report progress by a currently outstanding transaction.
*
* @param aTransaction The transaction reporting progress
* @param aEvent The event being notified
*/
void CQiQiHTTPEngine::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
{
switch (aEvent.iStatus)
{
case THTTPEvent::EGotResponseHeaders:
{
// HTTP response headers have been received.
// Pass status information to observer.
RHTTPResponse resp = aTransaction.Response();
// Get status code
TInt statusCode = resp.StatusCode();
// Get status text
RStringF statusStr = resp.StatusText();
HBufC* statusBuf = HBufC::NewLC(statusStr.DesC().Length());
statusBuf->Des().Copy(statusStr.DesC());
// 获取Session Id
RStringPool strPool = aTransaction.Session().StringPool();
RHTTPHeaders headers = resp.GetHeaderCollection();
RStringF sessionId = strPool.OpenFStringL(_L8("sessionId"));
CleanupClosePushL(sessionId);
TBuf8<KMaxSessionIdLength> fieldValBuf8;
THTTPHdrVal sessionIdVal;
TInt result = headers.GetField(sessionId, 0, sessionIdVal);
if (KErrNone == result)
{
fieldValBuf8.Copy(sessionIdVal.StrF().DesC().Left(32));
}
CleanupStack::PopAndDestroy(&sessionId);
// 根据返回消息头信息进行处理
iActive.ResponseStatusL(statusCode, fieldValBuf8);
CleanupStack::PopAndDestroy(statusBuf);
}
break;
case THTTPEvent::EGotResponseBodyData:
{
// Get text of response body
MHTTPDataSupplier* dataSupplier = aTransaction.Response().Body();
TPtrC8 ptr;
dataSupplier->GetNextDataPart(ptr);
// Convert to 16-bit descriptor
HBufC* buf = HBufC::NewLC(ptr.Length());
buf->Des().Copy(ptr);
// 保存Body数据
iActive.ResponseBodyDataL(*buf);
// Release buf
CleanupStack::PopAndDestroy(buf);
// Release the body data
dataSupplier->ReleaseData();
}
break;
case THTTPEvent::EResponseComplete:
{
}
break;
case THTTPEvent::ESucceeded:
{
iActive.ResponseReceivedL();
}
break;
default:
break;
}
}
/**
*/
TInt CQiQiHTTPEngine::MHFRunError(TInt aError, RHTTPTransaction /*aTransaction*/, const THTTPEvent& /*aEvent*/)
{
return aError;
}
/**
* Initiate a GET request
*
* @param aUri The URI to get
*/
void CQiQiHTTPEngine::GetRequestL(const TDesC& aUri, const TDesC8& aAccept)
{
// 解析URI
ParseUriL(aUri);
// 创建事务
iTransaction = iSession.OpenTransactionL(iUriParser, *this,
iSession.StringPool().StringF(HTTP::EGET, RHTTPSession::GetTable()));
// 设置请求头部
RHTTPHeaders headers = iTransaction.Request().GetHeaderCollection();
AddHeaderL(headers, HTTP::EUserAgent, KUserAgent);
AddHeaderL(headers, HTTP::EAccept, aAccept/*KAccept*/);
// 提交请求(异步)
iTransaction.SubmitL();
}
//
// Utility methods
//
/**
* Parse a URI
*
* @param aUri The URI to be parsed
*/
void CQiQiHTTPEngine::ParseUriL(const TDesC& aUri)
{
// Convert the URI to an 8-bit descriptor
// then set iUriParser to point at it
delete iUri;
iUri = NULL;
iUri = HBufC8::NewL(aUri.Length());
iUri->Des().Copy(aUri);
User::LeaveIfError(iUriParser.Parse(*iUri));
}
/**
* Add a header to a header set
*
* @param aHeaders The header set to be modified
* @param aHeaderField The name of the header to be added
* @param aHeaderValue The value for the header to be added
*/
void CQiQiHTTPEngine::AddHeaderL(RHTTPHeaders aHeaders, TInt aHeaderField, const TDesC8& aHeaderValue)
{
RStringPool stringPool = iSession.StringPool();
RStringF valStr = stringPool.OpenFStringL(aHeaderValue);
CleanupClosePushL(valStr);
THTTPHdrVal headerVal(valStr);
aHeaders.SetFieldL(stringPool.StringF(aHeaderField, RHTTPSession::GetTable()), headerVal);
CleanupStack::PopAndDestroy(&valStr);
//valStr.Close();
}
/**
* Cancel any outstanding transaction
*/
void CQiQiHTTPEngine::Cancel()
{
// Close() also cancels transaction (Cancel() can also be used but
// resources allocated by transaction must be still freed with Close())
iTransaction.Close();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -