存储HTTP的cookies
文章信息
- 详细描述
这里cookie是指从服务器端像客户端(浏览器)发送的一段信息。客户端可以存储在本地,并在请求时将此发回服务器。
根据cookie的类型可以将其长期存储或短期存储。Cookies用来包括指定会话下的登录或注册信息。
S60可以将cookie存储在Cookie管理组件中的一个私有文件夹中。如果第三方想访问这些cookie,则需要AllFiles权限。
- 解决方案
下列代码片段演示一个客户端如何解析http返回的头中有关cooke信息存储的内容:
_LIT8(KAccept, "*/*");
_LIT8(KAtext, "text/plain");
// Get request method string for HTTP GET
RStringF method =
iSession.StringPool().StringF(HTTP::EGET,RHTTPSession::GetTable());
iTransaction = iSession.OpenTransactionL(uri, *this, method);
RHTTPHeaders hdr = iTransaction.Request().GetHeaderCollection();
SetHeaderL(hdr, HTTP::EUserAgent, KUserAgent);
SetHeaderL(hdr, HTTP::EAccept, KAccept);
SetHeaderL(hdr, HTTP::ECookie, KAtext);
SetHeaderL(hdr, HTTP::ECookieName, KAtext);
SetHeaderL(hdr, HTTP::ECookieValue, KAtext);
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();
}
void CClientEngine::MHFRunL(RHTTPTransaction aTransaction,
const THTTPEvent& aEvent)
{
switch (aEvent.iStatus)
{
case THTTPEvent::EGotResponseHeaders:
{
RHTTPResponse resp1 = aTransaction.Response();
RStringPool strP = aTransaction.Session().StringPool();
RHTTPHeaders hdr = resp1.GetHeaderCollection();
THTTPHdrFieldIter it = hdr.Fields();
TBuf<512> fieldName16;
TBuf<512> fieldVal16;
while (it.AtEnd() == EFalse)
{
// Get the name of the next header field <br>
RStringTokenF fieldName = it();
RStringF fieldNameStr = strP.StringF(fieldName);
// Check it does indeed exist
THTTPHdrVal fieldVal;
if (hdr.GetField(fieldNameStr,0,fieldVal) == KErrNone)
{
RStringF wwwCookie = strP.StringF(
HTTP::ESetCookie, RHTTPSession::GetTable());
TInt mycookieCount = hdr.FieldPartsL(wwwCookie);
if (fieldNameStr == wwwCookie)
{
RStringF nameValStr;
RStringF valueValStr;
// Check the cookie name and value
RStringF name = strP.StringF(
HTTP::ECookieName, RHTTPSession::GetTable());
RStringF value = strP.StringF(HTTP::ECookieValue,
RHTTPSession::GetTable());
THTTPHdrVal nameVal, valueVal;
if (hdr.GetParam(wwwCookie, name, nameVal) == KErrNone)
{
nameValStr = strP.StringF(nameVal.StrF());
fieldName16.Copy(nameValStr.DesC());
}
if (hdr.GetParam(wwwCookie, value, valueVal) == KErrNone)
{
valueValStr = strP.StringF(valueVal.StrF());
fieldVal16.Copy(valueValStr.DesC());
}
...
// Create a cookie object with name, value and URI and save
// it as a file (for example, to app. private directory)
// URI can be obtained with:
// const TUriC8& requestUri = aTransaction.Request().URI();
}
}
// Advance the iterator
++it;
}
break;
}
...
}
}


(no comments yet)