examples/AppProts/exampleclient/httpexampleclient.cpp

00001 // Copyright (c) 2001-2009 Nokia Corporation and/or its subsidiary(-ies).
00002 // All rights reserved.
00003 // This component and the accompanying materials are made available
00004 // under the terms of "Eclipse Public License v1.0"
00005 // which accompanies this distribution, and is available
00006 // at the URL "http://www.eclipse.org/legal/epl-v10.html".
00007 //
00008 // Initial Contributors:
00009 // Nokia Corporation - initial contribution.
00010 //
00011 // Contributors:
00012 //
00013 // Description:
00014 //
00015 
00016 
00017 #include <uri8.h>
00018 #include <e32base.h>
00019 #include <http.h>
00020 #include <chttpformencoder.h>
00021 
00022 #include "httpexampleclient.h"
00023 #include "httpexampleutils.h"
00024 
00025 
00026 // format for output of data/time values
00027 _LIT(KDateFormat,"%D%M%Y%/0%1%/1%2%/2%3%/3 %:0%H%:1%T%:2%S.%C%:3");
00028 
00029 // File system root
00030 _LIT(KFileSystemRoot,"\\");
00031 
00032 // Standard headers used by default
00033 _LIT8(KUserAgent, "HTTPExampleClient (1.0)");
00034 _LIT8(KAccept, "*/*");
00035 
00036 _LIT(KHttpExampleClientPanic, "HTTP-EC");
00037 
00038 enum THttpExampleClientPanics
00039         {
00040         EReqBodySumitBufferNotAllocated,
00041         KBodyWithInvalidSize,
00042         KCouldntNotifyBodyDataPart
00043         };
00044 
00045 // Size of buffer used when submitting request bodies
00046 const TInt KMaxSubmitSize = 1024;
00047 const TInt KMaxHeaderNameLen = 32;
00048 const TInt KMaxHeaderValueLen = 128;
00049 
00050 
00051 //
00052 // Implementation of CHttpClient
00053 //
00054 
00055 
00056 // Supplied as the name of the test program to CHttpExampleUtils
00057 _LIT(KHttpExampleClientTestName, "HttpExample");
00058 
00059 CHttpClient::CHttpClient()
00060         : iReqBodySubmitBufferPtr(0,0)
00061         {
00062         // Initial timestamp is time now
00063         ResetTimeElapsed();
00064         }
00065 
00066 
00067 CHttpClient::~CHttpClient()
00068         {
00069         iSess.Close();
00070         iFileServ.Close();
00071         delete iReqBodySubmitBuffer;
00072         delete iTransObs;
00073         delete iFormEncoder;
00074         delete iUtils;
00075         }
00076 
00077 CHttpClient* CHttpClient::NewLC()
00078         {
00079         CHttpClient* me = new(ELeave) CHttpClient;
00080         CleanupStack::PushL(me);
00081         me->ConstructL();
00082         return me;
00083         }
00084 
00085 CHttpClient* CHttpClient::NewL()
00086         {
00087         CHttpClient* me = NewLC();
00088         CleanupStack::Pop(me);
00089         return me;
00090         }
00091 
00092 void CHttpClient::ConstructL()
00093         {
00094         iUtils = CHttpExampleUtils::NewL(KHttpExampleClientTestName);
00095         
00096         // Open the RHTTPSession
00097         iSess.OpenL();
00098 
00099         // Install this class as the callback for authentication requests
00100         InstallAuthenticationL(iSess);
00101         
00102         User::LeaveIfError(iFileServ.Connect());
00103         iTransObs = CHttpEventHandler::NewL(*iUtils);
00104         }
00105 
00106 void CHttpClient::StartClientL()
00107         {
00108         ResetTimeElapsed();
00109         TBuf<256> url;
00110         RStringPool strP = iSess.StringPool();
00111 
00112         // Repeat until user selects quit
00113         TBool done = EFalse;
00114         while (!done)
00115                 {
00116                 // Get user command from menu
00117                 iUtils->Test().Console()->ClearScreen();
00118                 _LIT(KSelectOption, " Select an option \n\n");
00119                 iUtils->Test().Printf(KSelectOption);
00120                 _LIT(KPossibleSelectionsText, " 1 Get \n 2 Post \n 3 Head \n 4 Trace \n 5 Toggle Verbose \n 6 Quit \n");
00121                 _LIT(KPossibleSelections,"123456");
00122                 TInt selection = iUtils->GetSelection(KPossibleSelectionsText, KPossibleSelections);
00123                 RStringF method;
00124                 iHasARequestBody = EFalse;
00125 
00126                 // Set the method to use and ask for a url
00127                 switch (selection)
00128                         {
00129                 case EGet: 
00130                         method = strP.StringF(HTTP::EGET,RHTTPSession::GetTable());
00131                         break;
00132                 case EPost:
00133                         method = strP.StringF(HTTP::EPOST,RHTTPSession::GetTable());
00134                         iHasARequestBody = ETrue; 
00135                         break;
00136                 case EHead: 
00137                         method = strP.StringF(HTTP::EHEAD,RHTTPSession::GetTable()); 
00138                         break;
00139                 case ETrace:
00140                         method = strP.StringF(HTTP::ETRACE,RHTTPSession::GetTable()); 
00141                         break;
00142                 case EToggleVerbosity: 
00143                         {
00144                         TBool verbose = iTransObs->Verbose();
00145                         iTransObs->SetVerbose(!verbose);
00146                         if (!verbose)
00147                                 User::InfoPrint(_L("Verbosity is ON "));
00148                         else
00149                                 User::InfoPrint(_L("Verbosity is OFF"));
00150                         }
00151                         break;
00152                 case EQuit:
00153                         done = ETrue;
00154                         break;
00155                 default: 
00156                          break;
00157                         } 
00158 
00159                 if (!done && (selection >= 0) && (selection <= 3))
00160                         {
00161                         // Get the URL
00162                         _LIT(KEnterUrl, "Enter Url");
00163                         iUtils->GetAnEntry(KEnterUrl, url);
00164                         if (url.Length() > 0) // back to main menu if we still have an empty URL
00165                                 {
00166                                 // Get a filename to submit as our request body, for methods that need one
00167                                 if (iHasARequestBody)
00168                                         {
00169                                         GetRequestBodyL(method);
00170                                         }
00171 
00172                                 // Start the method off
00173                                 TBuf8<256> url8;
00174                                 url8.Copy(url);
00175                                 InvokeHttpMethodL(url8, method);
00176                                 }
00177                         else
00178                                 {
00179                                 _LIT(KEmptyUrlErrorText, "You must supply a non empty url");
00180                                 iUtils->Test().Printf(KEmptyUrlErrorText);
00181                                 User::After(1000000);
00182                                 }
00183                         }
00184 
00185                 } // while
00186 
00187         // End of tests
00188         DisplayTimeElapsed();
00189         iUtils->PressAnyKey();
00190 }
00191 
00196 void CHttpClient::GetPostBodyManuallyL()
00197         {
00198         if (iFormEncoder)
00199                 {
00200                 delete iFormEncoder;
00201                 iFormEncoder = NULL;
00202                 }
00203 
00204         iFormEncoder = CHTTPFormEncoder::NewL(); 
00205         TBuf<256> name;
00206         TBuf<256> value;
00207         TBuf8<256> name8;
00208         TBuf8<256> value8;
00209         
00210         _LIT(KGetPostName, "Enter Name (END to finish)");
00211         _LIT(KGetPostValue, "Enter Value ");
00212         _LIT(KEnd, "END");
00213         do
00214                 {
00215                 iUtils->GetAnEntry(KGetPostName, name);
00216                 if (name.CompareF(KEnd) != 0)
00217                         {
00218                         iUtils->GetAnEntry(KGetPostValue, value);
00219                         name8.Copy(name);
00220                         value8.Copy(value);
00221                         iFormEncoder->AddFieldL(name8, value8);
00222                         }
00223                 }
00224                 while (name.CompareF(KEnd) != 0);
00225         }
00226 
00227 
00231 void CHttpClient::GetRequestBodyL(RStringF& aMethod)
00232         {
00233         if (aMethod== iSess.StringPool().StringF(HTTP::EPOST,RHTTPSession::GetTable()))
00234                 {
00235                 // get a post body by file or contruct manually?
00236                 _LIT(KConstructPostManually, "\n> Construct Post Manually?  Yes | No ");
00237                 _LIT(KYesNo, "YyNn");
00238                 TInt selection = iUtils->GetSelection(KConstructPostManually,KYesNo);
00239                 if (selection < 2) // 2 is NO
00240                         {
00241                         iManualPost = ETrue;
00242                         GetPostBodyManuallyL();
00243                         return;
00244                         }
00245                 // else carry on as usual and get post data from a file
00246                 }
00247 
00248         iManualPost = EFalse;
00249         _LIT(KRequestPathPrompt, "Enter path to request body file: ");
00250         iUtils->GetAnEntry(KRequestPathPrompt, iReqBodyFileName);
00251         _LIT(KRequestBodyContentType, "Enter request body content-type: ");
00252         iUtils->GetAnEntry(KRequestBodyContentType, iReqBodyContentType);
00253         iParsedFileName.Set(KFileSystemRoot,&iReqBodyFileName,NULL);
00254 
00255         // Check it exists and open a file handle
00256         if (iFileServ.IsValidName(iReqBodyFileName))
00257                 {
00258                 User::LeaveIfError(iReqBodyFile.Open(iFileServ, iParsedFileName.FullName(), EFileRead));
00259                 delete iReqBodySubmitBuffer;
00260                 iReqBodySubmitBuffer = NULL;
00261                 iReqBodySubmitBuffer = HBufC8::NewMaxL(KMaxSubmitSize);
00262                 iReqBodySubmitBufferPtr.Set(iReqBodySubmitBuffer->Des());
00263                 }
00264         else
00265                 {
00266                 _LIT(KFileNameNotValid, "The specified filename is not valid!.\n");
00267                 iUtils->Test().Printf(KFileNameNotValid);
00268                 }
00269         }
00270 
00271 TBool CHttpClient::GetNextDataPart(TPtrC8& aDataPart)
00272         {
00273         __ASSERT_DEBUG(iReqBodySubmitBuffer, User::Panic(KHttpExampleClientPanic, EReqBodySumitBufferNotAllocated));
00274         // Read from the request body file
00275         TBool retVal = EFalse;
00276         TInt err = iReqBodyFile.Read(iReqBodySubmitBufferPtr);
00277         if (err == KErrNone)
00278                 {
00279                 aDataPart.Set(iReqBodySubmitBufferPtr);
00280                 ++iDataChunkCount;
00281                 retVal = (iReqBodySubmitBufferPtr.Length() == 0);
00282                 }
00283         return retVal;
00284         }
00285 
00286 void CHttpClient::ReleaseData()
00287         {
00288         // Clear out the submit buffer
00289         TPtr8 buff = iReqBodySubmitBuffer->Des();
00290         buff.Zero();
00291         // Notify HTTP of more data available immediately, since it's being read from file
00292         TRAPD(err, iTrans.NotifyNewRequestBodyPartL());
00293         if (err != KErrNone)
00294                 User::Panic(KHttpExampleClientPanic, KCouldntNotifyBodyDataPart);
00295         }
00296 
00297 TInt CHttpClient::OverallDataSize()
00298         {
00299         TInt size = 0;
00300         TInt err = iReqBodyFile.Size(size);
00301         if (err < 0)
00302                 User::Panic(KHttpExampleClientPanic,KBodyWithInvalidSize);
00303 
00304         return size;
00305         }
00306 
00307 TInt CHttpClient::Reset()
00308         {
00309         return KErrNotSupported;
00310         }
00311 
00312 
00316 void CHttpClient::InvokeHttpMethodL(const TDesC8& aUri, RStringF aMethod)
00317         {
00318         // Set the protocol, before the first transaction gets started
00319 /*      if (iUseWspProtocol)
00320                 {
00321                 RHTTPConnectionInfo ci = iSess.ConnectionInfo();
00322                 ci.SetPropertyL(iSess.StringPool().StringF(HTTP::EProtocol,RHTTPSession::GetTable()),
00323                                                 THTTPHdrVal(iSess.StringPool().StringF(HTTP::EWSP,RHTTPSession::GetTable())));
00324                 }*/
00325 
00326         iDataChunkCount = 0;
00327         TUriParser8 uri; 
00328         uri.Parse(aUri);
00329         iTrans = iSess.OpenTransactionL(uri, *iTransObs, aMethod);
00330         RHTTPHeaders hdr = iTrans.Request().GetHeaderCollection();
00331 
00332         // Add headers appropriate to all methods
00333         SetHeaderL(hdr, HTTP::EUserAgent, KUserAgent);
00334         SetHeaderL(hdr, HTTP::EAccept, KAccept);
00335 
00336         // Add headers and body data for methods that use request bodies
00337         if (iHasARequestBody)
00338                 {
00339                 // Content type header
00340                 TBuf8<KMaxContentTypeSize> contTypeBuf;
00341                 contTypeBuf.Copy(iReqBodyContentType);
00342                 RStringF contTypeStr = iSess.StringPool().OpenFStringL(contTypeBuf);
00343                 THTTPHdrVal contType(contTypeStr);
00344                 hdr.SetFieldL(iSess.StringPool().StringF(HTTP::EContentType,RHTTPSession::GetTable()), contType);
00345                 contTypeStr.Close();
00346                 
00347                 MHTTPDataSupplier* dataSupplier = this;
00348                 if (iManualPost)
00349                         dataSupplier = iFormEncoder;
00350                 iTrans.Request().SetBody(*dataSupplier);
00351                 }
00352 
00353         // submit the transaction
00354         iTrans.SubmitL();
00355 
00356         // Start the scheduler, once the transaction completes or is cancelled on an error the scheduler will be
00357         // stopped in the event handler
00358         CActiveScheduler::Start();
00359 
00360         // all done
00361         iUtils->PressAnyKey();
00362 
00363         // close the request body file, if one was opened
00364         if (iHasARequestBody)
00365                 iReqBodyFile.Close();
00366         }
00367 
00368 void CHttpClient::SetHeaderL(RHTTPHeaders aHeaders, TInt aHdrField, const TDesC8& aHdrValue)
00369         {
00370         RStringF valStr = iSess.StringPool().OpenFStringL(aHdrValue);
00371         THTTPHdrVal val(valStr);
00372         aHeaders.SetFieldL(iSess.StringPool().StringF(aHdrField,RHTTPSession::GetTable()), val);
00373         valStr.Close();
00374         }
00375 
00376 void CHttpClient::ResetTimeElapsed()
00377 // Resets timestamp to time now
00378         {
00379         iLastTimeStamp.UniversalTime(); 
00380         }
00381 
00382 
00383 void CHttpClient::DisplayTimeElapsed()
00384 // Calculate elapsed time since last measurement, and display
00385         {
00386         TTime timeNow;
00387         timeNow.UniversalTime();
00388         TTimeIntervalMicroSeconds elapsedMicroSec =
00389                                                                         timeNow.MicroSecondsFrom(iLastTimeStamp);
00390         iLastTimeStamp = timeNow;
00391         iUtils->Test().Printf(
00392                 _L("Time elapsed since last measurement is: %d ms\n"),
00393                 elapsedMicroSec.Int64()/1000
00394                 );
00395         }
00396 
00397 
00402 TBool CHttpClient::GetCredentialsL(const TUriC8& aURI, RString aRealm, 
00403                                                                    RStringF aAuthenticationType,
00404                                                                    RString& aUsername, 
00405                                                                    RString& aPassword)
00406 
00407         {
00408         TBuf<80> scratch;
00409         TBuf8<80> scratch8;
00410         scratch8.Format(_L8("Enter credentials for URL %S, realm %S"), &aURI.UriDes(), &aRealm.DesC());
00411         scratch.Copy(scratch8);
00412         iUtils->Test().Printf(_L("%S\n"), &scratch);
00413         scratch.Copy(aAuthenticationType.DesC());
00414         iUtils->Test().Printf(_L("Using %S authentication\n"), &scratch);
00415         iUtils->GetAnEntry(_L("Username (or QUIT to give up): "), scratch);
00416         scratch8.Copy(scratch);
00417         if (scratch8.CompareF(_L8("quit")))
00418                 {
00419                 TRAPD(err, aUsername = aRealm.Pool().OpenStringL(scratch8));
00420                 if (!err)
00421                         {
00422                         iUtils->GetAnEntry(_L("Password: "), scratch);
00423                         scratch8.Copy(scratch);
00424                         TRAP(err, aPassword = aRealm.Pool().OpenStringL(scratch8));
00425                         if (!err)
00426                                 return ETrue;
00427                         }
00428                 }
00429         return EFalse;
00430         }
00431 
00432 
00433 //
00434 // Implementation of class CHttpEventHandler
00435 //
00436 
00437 void CHttpEventHandler::ConstructL()
00438         {
00439         User::LeaveIfError(iFileServ.Connect());
00440         }
00441 
00442 
00443 CHttpEventHandler::CHttpEventHandler(CHttpExampleUtils& aUtils) :
00444         iUtils(aUtils)
00445         {
00446         }
00447 
00448 
00449 CHttpEventHandler::~CHttpEventHandler()
00450         {
00451         iFileServ.Close();
00452         }
00453 
00454 
00455 CHttpEventHandler* CHttpEventHandler::NewLC(CHttpExampleUtils& aUtils)
00456         {
00457         CHttpEventHandler* me = new(ELeave)CHttpEventHandler(aUtils);
00458         CleanupStack::PushL(me);
00459         me->ConstructL();
00460         return me;
00461         }
00462 
00463 
00464 CHttpEventHandler* CHttpEventHandler::NewL(CHttpExampleUtils& aUtils)
00465         {
00466         CHttpEventHandler* me = NewLC(aUtils);
00467         CleanupStack::Pop(me);
00468         return me;
00469         }
00470 
00471 
00472 void CHttpEventHandler::SetVerbose(TBool aVerbose)
00473         {
00474         iVerbose = aVerbose;
00475         }
00476 
00477 
00478 TBool CHttpEventHandler::Verbose() const
00479         {
00480         return iVerbose;
00481         }
00482 
00483 
00484 void CHttpEventHandler::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
00485         {
00486         switch (aEvent.iStatus)
00487                 {
00488                 case THTTPEvent::EGotResponseHeaders:
00489                         {
00490                         // HTTP response headers have been received. We can determine now if there is
00491                         // going to be a response body to save.
00492                         RHTTPResponse resp = aTransaction.Response();
00493                         TInt status = resp.StatusCode();
00494                         RStringF statusStr = resp.StatusText();
00495                         TBuf<32> statusStr16;
00496                         statusStr16.Copy(statusStr.DesC());
00497                         iUtils.Test().Printf(_L("Status: %d (%S)\n"), status, &statusStr16);
00498 
00499                         // Dump the headers if we're being verbose
00500                         if (iVerbose)
00501                                 DumpRespHeadersL(aTransaction);
00502 
00503                         // Determine if the body will be saved to disk
00504                         iSavingResponseBody = EFalse;
00505                         TBool cancelling = EFalse;
00506                         if (resp.HasBody() && (status >= 200) && (status < 300) && (status != 204))
00507                                 {
00508                                 TInt dataSize = resp.Body()->OverallDataSize();
00509                                 if (dataSize >= 0)
00510                                         iUtils.Test().Printf(_L("Response body size is %d\n"), dataSize);
00511                                 else
00512                                         iUtils.Test().Printf(_L("Response body size is unknown\n"));
00513 
00514                                 TInt selection = iUtils.GetSelection(_L("\n> Save response to disk? Yes | No | Cancel"), _L("YyNnCc"));
00515                                 iSavingResponseBody = (selection < 2);
00516                                 cancelling = (selection == 4) || (selection == 5);
00517                                 }
00518 
00519                         // If we're cancelling, must do it now..
00520                         if (cancelling)
00521                                 {
00522                                 iUtils.Test().Printf(_L("\nTransaction Cancelled\n"));
00523                                 aTransaction.Close();
00524                                 CActiveScheduler::Stop();
00525                                 }
00526                         else if (iSavingResponseBody) // If we're saving, then open a file handle for the new file
00527                                 {
00528                                 iUtils.GetAnEntry(_L("Enter filename including path to save response body"), iRespBodyFileName);
00529                                 iParsedFileName.Set(KFileSystemRoot,&iRespBodyFileName,NULL);
00530 
00531                                 // Check it exists and open a file handle
00532                                 TInt valid = iFileServ.IsValidName(iRespBodyFileName);
00533                                 if (!valid)
00534                                         {
00535                                         iUtils.Test().Printf(_L("The specified filename is not valid!.\n"));
00536                                         iSavingResponseBody = EFalse;
00537                                         }
00538                                 else
00539                                         {
00540                                         TInt err = iRespBodyFile.Replace(iFileServ,
00541                                                                                                          iParsedFileName.FullName(),
00542                                                                                                          EFileWrite|EFileShareExclusive);
00543                                         if (err)
00544                                                 {
00545                                                 iSavingResponseBody = EFalse;
00546                                                 User::Leave(err);
00547                                                 }
00548                                         }
00549                                 }
00550 
00551                         } break;
00552                 case THTTPEvent::EGotResponseBodyData:
00553                         {
00554                         // Get the body data supplier
00555                         iRespBody = aTransaction.Response().Body();
00556 
00557                         // Some (more) body data has been received (in the HTTP response)
00558                         if (iVerbose)
00559                                 DumpRespBody(aTransaction);
00560                         else
00561                                 iUtils.Test().Printf(_L("*"));
00562 
00563                         // Append to the output file if we're saving responses
00564                         if (iSavingResponseBody)
00565                                 {
00566                                 TPtrC8 bodyData;
00567                                 TBool lastChunk = iRespBody->GetNextDataPart(bodyData);
00568                                 iRespBodyFile.Write(bodyData);
00569                                 if (lastChunk)
00570                                         iRespBodyFile.Close();
00571                                 }
00572 
00573                         // Done with that bit of body data
00574                         iRespBody->ReleaseData();
00575                         } break;
00576                 case THTTPEvent::EResponseComplete:
00577                         {
00578                         // The transaction's response is complete
00579                         iUtils.Test().Printf(_L("\nTransaction Complete\n"));
00580                         } break;
00581                 case THTTPEvent::ESucceeded:
00582                         {
00583                         iUtils.Test().Printf(_L("Transaction Successful\n"));
00584                         aTransaction.Close();
00585                         CActiveScheduler::Stop();
00586                         } break;
00587                 case THTTPEvent::EFailed:
00588                         {
00589                         iUtils.Test().Printf(_L("Transaction Failed\n"));
00590                         aTransaction.Close();
00591                         CActiveScheduler::Stop();
00592                         } break;
00593                 case THTTPEvent::ERedirectedPermanently:
00594                         {
00595                         iUtils.Test().Printf(_L("Permanent Redirection\n"));
00596                         } break;
00597                 case THTTPEvent::ERedirectedTemporarily:
00598                         {
00599                         iUtils.Test().Printf(_L("Temporary Redirection\n"));
00600                         } break;
00601                 default:
00602                         {
00603                         iUtils.Test().Printf(_L("<unrecognised event: %d>\n"), aEvent.iStatus);
00604                         // close off the transaction if it's an error
00605                         if (aEvent.iStatus < 0)
00606                                 {
00607                                 aTransaction.Close();
00608                                 CActiveScheduler::Stop();
00609                                 }
00610                         } break;
00611                 }
00612         }
00613 
00614 TInt CHttpEventHandler::MHFRunError(TInt aError, RHTTPTransaction /*aTransaction*/, const THTTPEvent& /*aEvent*/)
00615         {
00616         iUtils.Test().Printf(_L("MHFRunError fired with error code %d\n"), aError);
00617 
00618         return KErrNone;
00619         }
00620 
00621 
00622 void CHttpEventHandler::DumpRespHeadersL(RHTTPTransaction& aTrans)
00623         {
00624         RHTTPResponse resp = aTrans.Response();
00625         RStringPool strP = aTrans.Session().StringPool();
00626         RHTTPHeaders hdr = resp.GetHeaderCollection();
00627         THTTPHdrFieldIter it = hdr.Fields();
00628 
00629         TBuf<KMaxHeaderNameLen>  fieldName16;
00630         TBuf<KMaxHeaderValueLen> fieldVal16;
00631 
00632         while (it.AtEnd() == EFalse)
00633                 {
00634                 RStringTokenF fieldName = it();
00635                 RStringF fieldNameStr = strP.StringF(fieldName);
00636                 THTTPHdrVal fieldVal;
00637                 if (hdr.GetField(fieldNameStr,0,fieldVal) == KErrNone)
00638                         {
00639                         const TDesC8& fieldNameDesC = fieldNameStr.DesC();
00640                         fieldName16.Copy(fieldNameDesC.Left(KMaxHeaderNameLen));
00641                         switch (fieldVal.Type())
00642                                 {
00643                         case THTTPHdrVal::KTIntVal:
00644                                 iUtils.Test().Printf(_L("%S: %d\n"), &fieldName16, fieldVal.Int());
00645                                 break;
00646                         case THTTPHdrVal::KStrFVal:
00647                                 {
00648                                 RStringF fieldValStr = strP.StringF(fieldVal.StrF());
00649                                 const TDesC8& fieldValDesC = fieldValStr.DesC();
00650                                 fieldVal16.Copy(fieldValDesC.Left(KMaxHeaderValueLen));
00651                                 iUtils.Test().Printf(_L("%S: %S\n"), &fieldName16, &fieldVal16);
00652                                 }
00653                                 break;
00654                         case THTTPHdrVal::KStrVal:
00655                                 {
00656                                 RString fieldValStr = strP.String(fieldVal.Str());
00657                                 const TDesC8& fieldValDesC = fieldValStr.DesC();
00658                                 fieldVal16.Copy(fieldValDesC.Left(KMaxHeaderValueLen));
00659                                 iUtils.Test().Printf(_L("%S: %S\n"), &fieldName16, &fieldVal16);
00660                                 }
00661                                 break;
00662                         case THTTPHdrVal::KDateVal:
00663                                 {
00664                                 TDateTime date = fieldVal.DateTime();
00665                                 TBuf<40> dateTimeString;
00666                                 TTime t(date);
00667                                 t.FormatL(dateTimeString,KDateFormat);
00668 
00669                                 iUtils.Test().Printf(_L("%S: %S\n"), &fieldName16, &dateTimeString);
00670                                 } 
00671                                 break;
00672                         default:
00673                                 iUtils.Test().Printf(_L("%S: <unrecognised value type>\n"), &fieldName16);
00674                                 break;
00675                                 }
00676 
00677                         // Display realm for WWW-Authenticate header
00678                         RStringF wwwAuth = strP.StringF(HTTP::EWWWAuthenticate,RHTTPSession::GetTable());
00679                         if (fieldNameStr == wwwAuth)
00680                                 {
00681                                 // check the auth scheme is 'basic'
00682                                 RStringF basic = strP.StringF(HTTP::EBasic,RHTTPSession::GetTable());
00683                                 RStringF realm = strP.StringF(HTTP::ERealm,RHTTPSession::GetTable());
00684                                 THTTPHdrVal realmVal;
00685                                 if ((fieldVal.StrF() == basic) && 
00686                                         (!hdr.GetParam(wwwAuth, realm, realmVal)))
00687                                         {
00688                                         RStringF realmValStr = strP.StringF(realmVal.StrF());
00689                                         fieldVal16.Copy(realmValStr.DesC());
00690                                         iUtils.Test().Printf(_L("Realm is: %S\n"), &fieldVal16);
00691                                         }
00692                                 }
00693                         }
00694                 ++it;
00695                 }
00696         }
00697 
00698 void CHttpEventHandler::DumpRespBody(RHTTPTransaction& aTrans)
00699         {
00700         MHTTPDataSupplier* body = aTrans.Response().Body();
00701         TPtrC8 dataChunk;
00702         TBool isLast = body->GetNextDataPart(dataChunk);
00703         DumpIt(dataChunk);
00704         if (isLast)
00705                 iUtils.Test().Printf(_L("Got last data chunk.\n"));
00706         }
00707 
00708 
00709 void CHttpEventHandler::DumpIt(const TDesC8& aData)
00710 //Do a formatted dump of binary data
00711         {
00712         // Iterate the supplied block of data in blocks of cols=80 bytes
00713         const TInt cols=16;
00714         TInt pos = 0;
00715         TBuf<KMaxFileName - 2> logLine;
00716         TBuf<KMaxFileName - 2> anEntry;
00717         const TInt dataLength = aData.Length();
00718         while (pos < dataLength)
00719                 {
00720                 //start-line hexadecimal( a 4 digit number)
00721                 anEntry.Format(TRefByValue<const TDesC>_L("%04x : "), pos);
00722                 logLine.Append(anEntry);
00723 
00724                 // Hex output
00725                 TInt offset;
00726                 for (offset = 0; offset < cols; ++offset)
00727                         {
00728                         if (pos + offset < aData.Length())
00729                                 {
00730                                 TInt nextByte = aData[pos + offset];
00731                                 anEntry.Format(TRefByValue<const TDesC>_L("%02x "), nextByte);
00732                                 logLine.Append(anEntry);
00733                                 }
00734                         else
00735                                 {
00736                                 //fill the remaining spaces with blanks untill the cols-th Hex number 
00737                                 anEntry.Format(TRefByValue<const TDesC>_L("   "));
00738                                 logLine.Append(anEntry);
00739                                 }
00740                         }
00741                         anEntry.Format(TRefByValue<const TDesC>_L(": "));
00742                         logLine.Append(anEntry);
00743 
00744                 // Char output
00745                 for (offset = 0; offset < cols; ++offset)
00746                         {
00747                         if (pos + offset < aData.Length())
00748                                 {
00749                                 TInt nextByte = aData[pos + offset];
00750                                 if ((nextByte >= ' ') && (nextByte <= '~'))
00751                                         {
00752                                         anEntry.Format(TRefByValue<const TDesC>_L("%c"), nextByte);
00753                                         logLine.Append(anEntry);
00754                                         }
00755                                 else
00756                                         {
00757                                         anEntry.Format(TRefByValue<const TDesC>_L("."));
00758                                         logLine.Append(anEntry);
00759                                         }
00760                                 }
00761                         else
00762                                 {
00763                                 anEntry.Format(TRefByValue<const TDesC>_L(" "));
00764                                 logLine.Append(anEntry);
00765                                 }
00766                         }
00767                         iUtils.Test().Printf(TRefByValue<const TDesC>_L("%S\n"), &logLine);     
00768                         logLine.Zero();
00769 
00770                 // Advance to next  byte segment (1 seg= cols)
00771                 pos += cols;
00772                 }
00773         }
00774 
00775 
00776 //
00777 // Main implementation
00778 //
00779 
00780 LOCAL_D void TestL()
00781 // Create a test object, invoke the tests using it and remove
00782         {
00783         // Start C32 and initalize some device drivers. This is necessary when running a test console as these won't 
00784         // have been started
00785         CHttpExampleUtils::InitCommsL();
00786 
00787         // create an active scheduler to use
00788         CActiveScheduler* scheduler = new(ELeave) CActiveScheduler();
00789         CleanupStack::PushL(scheduler);
00790         CActiveScheduler::Install(scheduler);
00791 
00792         // Create and start the client
00793         CHttpClient* httpCli = CHttpClient::NewLC();
00794         httpCli->StartClientL();
00795 
00796         CleanupStack::PopAndDestroy(2); // httpCli, scheduler
00797         }
00798 
00799 
00800 GLDEF_C TInt E32Main()
00801 // Main program - run the tests within a TRAP harness, reporting any errors that
00802 // occur via the panic mechanism. Test for memory leaks using heap marking.
00803         {
00804         __UHEAP_MARK;
00805         CTrapCleanup* tc=CTrapCleanup::New();
00806 
00807         TRAPD(err,TestL());
00808         if (err!=KErrNone)
00809                 User::Panic(_L("Test failed with error code: %i"), err);
00810         delete tc;
00811         __UHEAP_MARKEND;
00812         return KErrNone;
00813         }
00814 
00815 
00816 

Generated on Thu Jan 21 10:32:55 2010 for TB10.1 Example Applications by  doxygen 1.5.3