头文件:
/*
* ============================================================================
* Name : ExampleClientEngine.h
* Part of : HTTP Example
* Created : 11/14/2003 by Forum Nokia
* Implementation notes:
*
*
* Version : 1.0
* Copyright: Nokia Corporation
* ============================================================================
*/
#ifndef __EXAMPLECLIENTENGINE_H__
#define __EXAMPLECLIENTENGINE_H__
#include "BaseView.h"
#include <coecntrl.h>
#include <http\mhttpdatasupplier.h>
#include <http\mhttptransactioncallback.h>
#include <http\mhttpauthenticationcallback.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:
/*
* ClientEvent()
*
* Called when event occurs in CClientEngine.
*
* Params:
* aEventDescription: A event in textual format, e.g.
* "Transaction Successful"
*
* Returns:
* -
*
*/
virtual void ClientEvent(const TDesC& aEventDescription) = 0;
/*
* ClientBodyReceived()
*
* Called when a part of the HTTP body is received.
*
* Params:
* aBodyData: Part of the body data received. (e.g. part of
* the received HTML page)
*
* Returns:
* -
*
*/
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:
/*
* NewL()
*
* Create a CClientEngine object.
*
* Params:
* iObserver:
*
* Returns:
* A pointer to the created instance of CClientEngine
*
*/
static CClientEngine* NewL(MClientObserver& iObserver);
/*
* NewLC()
*
* Create a CClientEngine object.
*
* Params:
* iObserver:
*
* Returns:
* A pointer to the created instance of CClientEngine
*
*/
static CClientEngine* NewLC(MClientObserver& iObserver);
/*
* ~CClientEngine()
*
* Destroy the object
*
* Params:
* -
*
* Returns:
* -
*
*/
~CClientEngine();
void SetFile(TDesC& aFileName);
void HttpDownload(TDesC& aUrl);
/*
* IssueHTTPGetL()
*
* Starts a new HTTP GET transaction.
*
* Params:
* aUri: URI to get. (e.g.
http://host.org")
*
* Returns:
* -
*
*/
void IssueHTTPGetL(const TDesC8& aUri);
/*
* IssueHTTPPostL()
*
* Starts a new HTTP POST transaction.
*
* Params:
* aUri: URI where to post the data (e.g.
http://host.org")
* aContentType: Content type of the body, e.g. "text/plain"
* aBody: Body data for the transaction.
*
* Returns:
* -
*
*/
void IssueHTTPPostL(const TDesC8& aUri,
const TDesC8& aContentType,
const TDesC8& aBody);
/*
* CancelTransaction()
*
* Closes currently running transaction and frees resources related to it.
*
* Params:
* -
*
* Returns:
* -
*
*/
void CancelTransaction();
/*
* IsRunning()
*
* Checks if the transaction is running.
*
* Params:
* -
*
* Returns:
* ETrue, if transaction is currently running.
*
*/
inline TBool IsRunning() { return iRunning; };
private:
/*
* ConstructL()
*
* Perform the second phase construction of a CClientEngine object.
*
* Params:
* -
*
* Returns:
* -
*
*/
void ConstructL();
/*
* CClientEngine()
*
* Perform the first phase of two phase construction.
*
* Params:
* iObserver:
*
* Returns:
* -
*
*/
CClientEngine(MClientObserver& iObserver);
/*
* SetHeaderL()
*
* Sets header value of an HTTP request.
*
* Params:
* aHeaders: Headers of the HTTP request
* aHdrField: Enumerated HTTP header field, e.g. HTTP::EUserAgent
* aHdrValue: New value for header field
*
* Returns:
* -
*
*/
void SetHeaderL(RHTTPHeaders aHeaders, TInt aHdrField,
const TDesC8& aHdrValue);
/*
* From MHTTPSessionEventCallback
*/
private:
/*
* MHFRunL()
*
* Called by framework to notify about transaction events.
*
* Params:
* aTransaction: Transaction, where the event occured.
* aEvent: Occured event.
*
* Returns:
* -
*
*/
void MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent);
/*
* MHFRunError()
*
* Called by framework when *leave* occurs in handling of transaction event.
*
* Params:
* aError: The leave code that occured.
* aTransaction: The transaction that was being processed when leave
* occured.
* aEvent: The event that was being processed when leave
* occured.
*
* Returns:
* KErrNone, if the error was handled. Otherwise the value of aError, or
* some other error value. Returning error value causes causes
* HTTP-CORE 6 panic.
*
*/
TInt MHFRunError( TInt aError,
RHTTPTransaction aTransaction,
const THTTPEvent& aEvent);
/*
* From MHTTPDataSupplier (needed for HTTP POST)
*/
private:
/*
* ReleaseData()
*
* Called by framework to allow data supplier to release resources
* related to previous data part.
*
* Params:
* -
*
* Returns:
* -
*
*/
void ReleaseData();
/*
* GetNextDataPart()
*
* Called when next data part is needed.
*
* Params:
* aDataPart: Must be set to point to the next data part.
*
* Returns:
* ETrue if the provided data part is the last one. If more data parts
* are needed after the provided one, return EFalse.
*
*/
TBool GetNextDataPart(TPtrC8& aDataPart);
/*
* Reset()
*
* Called by framework to reset the data supplier to its initial state.
*
* Params:
* -
*
* Returns:
* KErrNone if successfull.
*
*/
TInt Reset();
/*
* OverallDataSize()
*
* Called by framework when it needs to know the size of the
* body data.
*
* Params:
* -
*
* Returns:
* Size of the data, or KErrNotFound (or KErrNotSupported)
* if the size of the data is not known.
*
*/
TInt OverallDataSize();
/*
* From MHTTPAuthenticationCallback (needed for HTTP authentication)
*/
private:
/*
* GetCredentialsL()
*
* Called by framework when username and password for requested URI is
* needed.
*
* Params:
* aURI: The URI being requested (e.g. "
http://host.org")
* aRealm: The realm being requested (e.g. "
user@host.org")
* aAuthenticationType: Authentication type. (e.g. "Basic")
* aUsername: Given user name.
* aPassword: Given password.
*
* Returns:
* A pointer to the created document
*
*/
TBool GetCredentialsL( const TUriC8& aURI,
RString aRealm,
RStringF aAuthenticationType,
RString& aUsername,
RString& aPassword);
TBool CClientEngine::SaveToFile(TPtrC8* pData);
private:
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
TBuf<256> iFileName;
TBuf<256> iFileNameTemp;
};
#endif // __EXAMPLECLIENTENGINE_H__
实现:
/*
* ============================================================================
* Name : ExampleClientEngine.cpp
* Part of : HTTP Example
* Created : 11/14/2003 by Forum Nokia
* Implementation notes:
*
*
* Version : 1.0
* Copyright: Nokia Corporation
* ============================================================================
*/
#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 <ExampleClient.rsg>
//#include "ExampleClient.pan"
//#include "ExampleClient.hrh"
#include "ClientEngine.h"
#include "logger.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, "*/*");
// Schemes for given uris
_LIT(KHttpPrefix, "http://");
_LIT8(KHttpPrefix8, "http://");
// HTTPS schemes
_LIT(KHttpsPrefix, "https://");
_LIT8(KHttpsPrefix8, "https://");
// ----------------------------------------------------------------------------
// 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();
delete iPostData;
iPostData = NULL;
}
// ----------------------------------------------------------------------------
// 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)
{
// 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)
{
// 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<32> statusText;
statusText.Copy(resp.StatusText().DesC());
TBuf<256> text;
_LIT(KHeaderReceived, "Header received. Status: %d %S");
text.Format(KHeaderReceived, status, &statusText);
iFileNameTemp = iFileName;
iFileNameTemp.Append(_L(".txt"));
//LOGF(_L("header:%S"),&iFileNameTemp);
//LOGF(_L("header:%S"),&text);
//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
// one.
TBool isLast = body->GetNextDataPart(dataChunk);
iObserver.ClientBodyReceived(dataChunk);
TBuf<64> text;
_LIT(KBodyPartReceived, "%d bytes received... ");
text.Format(KBodyPartReceived, dataChunk.Length());
//打开文件
if ( iFileName.Length() > 0 )
{
////////////////////////////
RFs& fs = CEikonEnv::Static()->FsSession();
fs.Connect();
//LOGF(_L("file:%S \n"),&iFileName);
RFile file;
TInt err = file.Open(fs, iFileNameTemp, EFileWrite | EFileShareExclusive);
if ( err == KErrNone )
{
TInt pos = 0;
file.Seek(ESeekEnd, pos);
} else if ( err == KErrNotFound )
{
//LOG(_L("Create file \n"));
file.Create(fs, iFileNameTemp,
EFileWrite | EFileShareExclusive);
}
//写入文件
//LOG(_L("write file \n"));
User::LeaveIfError(file.Write(dataChunk));
User::LeaveIfError(file.Flush());
//LOG(_L("close file \n"));
file.Close();
fs.Close();
/////////////////////////////
}
//iObserver.ClientEvent(text);
// NOTE: isLast may not be ETrue even if last data part received.
// (e.g. multipart response without content length field)
// Use EResponseComplete to reliably determine when body is completely
// received.
if (isLast)
{
//_LIT(KBodyReceived,"Body received");
//iObserver.ClientEvent(KBodyReceived);
}
// Always remember to release the body data.
body->ReleaseData();
}
break;
case THTTPEvent::EResponseComplete:
{
// Indicates that header & body of response is completely received.
// No further action here needed.
//_LIT(KTransactionComplete, "Transaction Complete");
//iObserver.ClientEvent(KTransactionComplete);
}
break;
case THTTPEvent::ESucceeded:
{
// Indicates that transaction succeeded.
_LIT(KTransactionSuccessful, "Transaction Successful");
//////////////////////////////
{
//删除原来的文件,将新文件改名
RFs& fs = CEikonEnv::Static()->FsSession();
fs.Connect();
fs.Delete(iFileName);
fs.Rename(iFileNameTemp,iFileName);
fs.Close();
LOG(_L("CClientEngine::MHFRunL THTTPEvent::ESucceeded \n"));
}
//////////////////////////////
// Transaction can be closed now. It‘s not needed anymore.
aTransaction.Close();
iRunning = EFalse;
iObserver.ClientEvent(iFileName);//iFileName
}
break;
case THTTPEvent::EFailed:
{
// Transaction completed with failure.
//_LIT(KTransactionFailed, "Transaction Failed");
//iObserver.ClientEvent(KTransactionFailed);
RFs& fs = CEikonEnv::Static()->FsSession();
fs.Connect();
fs.Delete(iFileNameTemp);
fs.Close();
LOG(_L("CClientEngine::THTTPEvent::EFailed \n"));
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<64> 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<64> 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 example
// 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;
// When sending data in multiple parts we must notify the framework here:
// (the framework can call GetNextDataPart() when we notify it by calling
// NotifyNewRequestBodyPartL())
/*
// Not needed unless we send data in multiple parts
TRAPD(err, iTransaction.NotifyNewRequestBodyPartL());
if (err != KErrNone)
Panic(EClientEngine);
*/
}
// ----------------------------------------------------------------------------
// 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::GetCredentialsL()
//
// Inherited from MHTTPAuthenticationCallback
// Called by framework when we requested authenticated page and framework
// needs to know username and password.
// ----------------------------------------------------------------------------
TBool CClientEngine::GetCredentialsL(const TUriC8& aURI,
RString aRealm,
RStringF aAuthenticationType,
RString& aUsername,
RString& aPassword)
{
// aURI, aReal and aAuthenticationType are informational only. We only need
// to set aUsername and aPassword and return ETrue, if aUsername and
// aPassword are provided by user.
// Informational only
TBuf<128> authType;
TBuf<128> uri;
TBuf<256> authText;
authType.Copy(aAuthenticationType.DesC());
uri.Copy(aURI.UriDes());
_LIT(KAuthRequired, "%S requires %S authentication.");
authText.Format(KAuthRequired, &uri, &authType);
_LIT(KAuthNote, "Authentication required.");
CEikonEnv::Static()->InfoWinL(KAuthNote, authText);
// Query user name and password
TBuf<256> userName;
TBuf<256> password;
CAknMultiLineDataQueryDialog* dlg =
CAknMultiLineDataQueryDialog::NewL(userName, password);
//if (!dlg->ExecuteLD(R_DIALOG_USER_PASSWORD_QUERY))
// return EFalse; // No credentials given; must return EFalse
// Set aUsername and aPassword
TBuf8<256> temp;
temp.Copy(userName);
TRAPD(err, aUsername = aRealm.Pool().OpenStringL(temp));
if (!err)
{
temp.Copy(password);
TRAP(err, aPassword = aRealm.Pool().OpenStringL(temp));
if (!err) return ETrue;
}
// Return ETrue if user has given credentials (username and password),
// otherwise EFlase
return EFalse;
}
TBool CClientEngine::SaveToFile(TPtrC8* pData)
{
/*
//打开文件
RFs& fs = CEikonEnv::Static()->FsSession();
fs.Connect();
RFile file;
TInt err = file.Open(fs, iFileName, EFileWrite | EFileShareExclusive);
if ( err == KErrNone )
{
TInt pos = 0;
file.Seek(ESeekEnd, pos);
} else if ( err == KErrNotFound )
{
file.Create(fs, iFileName,
EFileWrite | EFileShareExclusive);
}
//写入文件
User::LeaveIfError(file.Write(pData));
User::LeaveIfError(file.Flush());
file.Close();
fs.Close();
*/
}
void CClientEngine::SetFile(TDesC& aFileName)
{
if ( aFileName.Length() <= 0 )
return;
iFileName.Format(aFileName);
}
void CClientEngine::HttpDownload(TDesC& aUrl)
{
if ( aUrl.Length() <= 0 )
return;
TBuf<256> tempUrl;
TBuf8<256> uri8;
CancelTransaction();
tempUrl.Format(aUrl);
tempUrl.LowerCase();
if(tempUrl.Find(KHttpPrefix) == KErrNotFound
&& tempUrl.Find(KHttpsPrefix) == KErrNotFound)
{
// If the uri does not contain http or https,
// use the default, "http://"
uri8.Append(KHttpPrefix8);
uri8.Append(tempUrl);
} else
{
//LOGF(_L("DownUrl-6:%S"),&tempUrl);
uri8.Copy(tempUrl);
LOG(_L("DownUrl-7"));
}
// Start transaction
LOG(_L("uri8 \n"));
IssueHTTPGetL(uri8);
/*
if ( aUrl.Length() <= 0 )
return;
TBuf<256> tempUrl;
TBuf8<256> uri8;
LOGF(_L("DownUrl-6:%S"),&aUrl);
CancelTransaction();
LOGF(_L("DownUrl-7:%S"),&aUrl);
tempUrl.Format(aUrl);
LOGF(_L("DownUrl-8:%S"),&aUrl);
tempUrl.LowerCase();
TInt state=CCnvCharacterSetConverter::KStateDefault ;
CCnvCharacterSetConverter* iConv ;
RFs fSession;
User::LeaveIfError(fSession.Connect());
iConv = CCnvCharacterSetConverter::NewLC();
if(iConv->PrepareToConvertToOrFromL(KCharacterSetIdentifierGbk,fSession)!=CCnvCharacterSetConverter::EAvailable)
{
fSession.Close();
User::Leave(KErrNotSupported);
}
HBufC8* iInfoText = HBufC8::NewL(tempUrl.Length());//要不要 除以 2?
TPtr8 ptr8 = iInfoText->Des();
iConv->ConvertFromUnicode(ptr8, tempUrl, state) ;
CleanupStack::PopAndDestroy() ;
fSession.Close();
LOGF(_L("DownUrl-9:%S"),&aUrl);
if(tempUrl.Find(KHttpPrefix) == KErrNotFound
&& tempUrl.Find(KHttpsPrefix) == KErrNotFound)
{
// If the uri does not contain http or https,
// use the default, "http://"
uri8.Append(KHttpPrefix8);
uri8.Append(tempUrl);
}
else
{
//LOGF(_L("ptr8:%s \n"),iInfoText->Des());
//uri8.Copy(tempUrl);
char szUrl[256] = {0};
strncpy(szUrl,(char*)ptr8.Ptr(),iInfoText->Length());
uri8.Copy(ptr8);
//uri8.Format("%s",szUrl);
}
SafeDelPtr(iInfoText);
// Start transaction
LOGF(_L("uri8:%s \n"),uri8);
IssueHTTPGetL(uri8);
*/
}