Пример #1
0
// ----------------------------------------------------------------------------
// 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
			// one.
			TBool isLast = body->GetNextDataPart(dataChunk);
			iObserver.ClientBodyReceived(dataChunk);

			TBuf<KInfotextBufferSize> text;
			_LIT(KBodyPartReceived, "%d bytes received... ");
			text.Format(KBodyPartReceived, dataChunk.Length());
			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");
			iObserver.ClientEvent(KTransactionSuccessful);

			// Transaction can be closed now. It's not needed anymore.
			aTransaction.Close();
			iRunning = EFalse;
			}
			break;

		case THTTPEvent::EFailed:
			{
			// Transaction completed with failure.
			_LIT(KTransactionFailed, "Transaction Failed");
			iObserver.ClientEvent(KTransactionFailed);
			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<KInfotextBufferSize> 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;
		}
	}
Пример #2
0
void CHttpEventHandler::MHFRunL(RHTTPTransaction aTransaction, const THTTPEvent& aEvent)
	{
	switch (aEvent.iStatus)
		{
		case THTTPEvent::EGotResponseHeaders:
			{
			// HTTP response headers have been received. We can determine now if there is
			// going to be a response body to save.
			RHTTPResponse resp = aTransaction.Response();
			TInt status = resp.StatusCode();
			
			if (iVerbose)
			{
				RStringF statusStr = resp.StatusText();
				TBuf<32> statusStr16;
				statusStr16.Copy(statusStr.DesC());
				iTest->Console()->Printf(_L("Status: %d (%S)\n"), status, &statusStr16);

				// Dump the headers if we're being verbose
				DumpRespHeadersL(aTransaction);
			}
			// Determine if the body will be saved to disk
			iSavingResponseBody = EFalse;
			if (resp.HasBody() && (status >= 200) && (status < 300) && (status != 204))
			{
				if (iVerbose)
				{
					TInt dataSize = resp.Body()->OverallDataSize();
					if (dataSize >= 0)
						iTest->Console()->Printf(_L("Response body size is %d\n"), dataSize);
					else
						iTest->Console()->Printf(_L("Response body size is unknown\n"));
				}
				iSavingResponseBody = ETrue;
			}
			else
			{
				if (iVerbose)
					iTest->Console()->Printf(_L("Response status is bad\n"));
			}

			if ((status >= 200) && (status < 300) && (status != 204))
			{
				ParseCookieL(aTransaction);
			}
			
			if (iSavingResponseBody) // If we're saving, then open a file handle for the new file
			{
				if ( iUsingFile )
				{
					iHttpFileManager->GetNewFile(iRespBodyFilePath, iRespBodyFileName, EFalse);
					
					// Check it exists and open a file handle
					TInt valid = iFileServ.IsValidName(iRespBodyFilePath);
					if (!valid)
					{
						if (iVerbose)
							iTest->Console()->Printf(_L("The specified filename is not valid!.\n"));
						
						iSavingResponseBody = EFalse;
					}
					else
					{
						TInt err = iRespBodyFile.Create(iFileServ,
													  iRespBodyFilePath,
													  EFileWrite|EFileShareExclusive);
						if (err)
						{
							iSavingResponseBody = EFalse;
							User::Leave(err);
						}
					}
				}
				else
				{
					TInt dataSize = resp.Body()->OverallDataSize();
					
					if ( iResBodyBuffer )
						delete iResBodyBuffer;
						
					iResBodyBuffer = NULL;
					
					if ( dataSize > 50 * 1024) //skip large chunks of data
					{
						iSavingResponseBody = false;
						//try to stop current connection
						if (iVerbose)
							iTest->Console()->Printf(_L("Transaction Failed\n"));
						aTransaction.Close();
						CActiveScheduler::Stop();
					}
					else
					{
						iResBodyBuffer = HBufC8::NewMaxL(dataSize);
						iResBodyBufferPtr.Set(iResBodyBuffer->Des());
					}					
					iCurPos = 0;
				}
			}
			
		} break;
		case THTTPEvent::EGotResponseBodyData:
			{
			// Get the body data supplier
			iRespBody = aTransaction.Response().Body();

			// Some (more) body data has been received (in the HTTP response)
			if (iVerbose)
				DumpRespBody(aTransaction);
			
			// Append to the output file if we're saving responses
			if (iSavingResponseBody)
			{
				TPtrC8 bodyData;
				TBool lastChunk = iRespBody->GetNextDataPart(bodyData);
								
				if ( iUsingFile )
				{
					iRespBodyFile.Write(bodyData);
					if (lastChunk)
					{
						iRespBodyFile.Flush();
						iRespBodyFile.Rename(iRespBodyFileName);
						iRespBodyFile.Close();
					}
				}
				else
				{
					Mem::Copy((void*)(iResBodyBuffer->Ptr()+iCurPos), (void*)bodyData.Ptr(), bodyData.Size());
					iCurPos += bodyData.Size();
				}
			}

			// Done with that bit of body data
			iRespBody->ReleaseData();
			} break;
		case THTTPEvent::EResponseComplete:
			{
			// The transaction's response is complete
			if (iVerbose)
				iTest->Console()->Printf(_L("\nTransaction Complete\n"));
			} break;
		case THTTPEvent::ESucceeded:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Transaction Successful\n"));
			aTransaction.Close();
			CActiveScheduler::Stop();
			} break;
		case THTTPEvent::EFailed:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Transaction Failed\n"));
			aTransaction.Close();
			CActiveScheduler::Stop();
			} break;
		case THTTPEvent::ERedirectedPermanently:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Permanent Redirection\n"));
			} break;
		case THTTPEvent::ERedirectedTemporarily:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("Temporary Redirection\n"));
			} break;
		default:
			{
			if (iVerbose)
				iTest->Console()->Printf(_L("<unrecognised event: %d>\n"), aEvent.iStatus);
			// close off the transaction if it's an error
			if (aEvent.iStatus < 0)
				{
				aTransaction.Close();
				CActiveScheduler::Stop();
				}
			} break;
		}
	}
void UPPayHttpConnection::ParaseResponseHeaders(RHTTPResponse resp)
{
	RHTTPHeaders headers = resp.GetHeaderCollection();
	THTTPHdrVal aHeaderValue;
	iStatusCode = resp.StatusCode();
	if (iStatusCode >= 200 && iStatusCode < 300)
	{
		
		RStringF contLength = stringPool.OpenFStringL(_L8("Content-Length"));
		headers.GetField(contLength, 0, aHeaderValue);
		contLength.Close();
		if (aHeaderValue.Type() == THTTPHdrVal::KTIntVal)
		{
			iContentLength = aHeaderValue.Int();
		}
		else
		{
			iContentLength = 200 * 1024;
		}
		//		if(iContentStartPos != 0)
		//		{
		//			HBufC8* fieldValBuf = HBufC8::NewLC(KMaxHeaderValueLength);
		//			RStringF  contentrange= stringPool.OpenFStringL(_L8("Content-Range"));
		//			TPtrC8 rawField(fieldValBuf->Des());
		//			if(headers.GetRawField(contentrange,rawField)==KErrNone)
		//			{
		//				fieldValBuf->Des().Zero();
		//			}
		//			contentrange.Close ( );
		//			CleanupStack::PopAndDestroy(fieldValBuf);
		//		}
	}
	//
	//	else
	//	{
	//		Stop(); 
	//		iObserver.StateChange(EHttpError);
	//	}

	if (response_header)
	{
		delete response_header;
	}
	response_header = HBufC8::NewL(2048);
	Mem::FillZ((void*) response_header->Ptr(), 2048);
	TPtr8 headPtr = response_header->Des();
	TVersion ver = resp.Version();
	headPtr.AppendFormat(_L8("HTTP/%d.%d %d "), ver.iMajor, ver.iMinor, iStatusCode);
	headPtr.Append(resp.StatusText().DesC());
	headPtr.Append(add2);

	RHTTPHeaders hdr = resp.GetHeaderCollection();
	THTTPHdrFieldIter it = hdr.Fields();
	THTTPHdrVal fieldVal;
	HBufC8* fieldValBuf = HBufC8::NewLC(KMaxHeaderValueLength);
	while (it.AtEnd() == EFalse)
	{
		RStringTokenF fieldName = it();
		RStringF fieldNameStr = stringPool.StringF(fieldName);
		TPtrC8 rawField(fieldValBuf->Des());
		if (hdr.GetRawField(fieldNameStr, rawField) == KErrNone)
		{
			headPtr.Append(fieldNameStr.DesC());
			headPtr.Append(add1);
			headPtr.Append(rawField);
			headPtr.Append(add2);
			fieldValBuf->Des().Zero();
		}
		++it;
	}
	CleanupStack::PopAndDestroy(fieldValBuf);
	
	if (iStatusCode == 301 || iStatusCode == 302)
	{
		if (iObserver)
		{
			iObserver->StateChange(ERedirect);
		}
	}
}
Пример #4
0
void CSTTrackerConnection::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.

			LWRITELN(iLog, _L("[Trackerconnection] Got HTTP headers"));
			// Get HTTP status code from header (e.g. 200)
			RHTTPResponse resp = aTransaction.Response();
			TInt status = resp.StatusCode();
			
			if (status != 200) // ERROR, hiba esetén mi legyen? 404-et lekezelni!
			{
				LWRITE(iLog, _L("[Trackerconnection] Error, status = "));
				TBuf<20> numBuf;
				numBuf.Num(status);
				LWRITELN(iLog, numBuf);
				Cancel();
				if (iObserver)
					iObserver->TrackerConnectionFailedL();
				break;
			}

			// Get status text (e.g. "OK")
			HLWRITE(iLog, _L("[Trackerconnection] Status text = "));
			TBuf<32> statusText;
			statusText.Copy(resp.StatusText().DesC());
			HLWRITELN(iLog, statusText);
			
			
			#ifdef LOG_TO_FILE
			RHTTPHeaders headers = 
				aTransaction.Response().GetHeaderCollection();		
			THTTPHdrFieldIter i =
				headers.Fields();
			for (i.First(); !(i.AtEnd()); ++i)
			{
				RStringF header = iSession.StringPool().StringF(i());
				
				if ((header.DesC() == _L8("Content-Type")))
				{
					HLWRITE(iLog, header.DesC());
					HLWRITE(iLog, _L(": "));
					THTTPHdrVal	val;
					headers.GetField(header, 0, val);
					RStringF value = val.StrF();
					HLWRITELN(iLog, value.DesC());
				}
				else
					HLWRITELN(iLog, header.DesC());
			}
						
			#endif
		}
		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);
			
			//iDownloadedSize += dataChunk.Size();						
			
			HLWRITELN(iLog, _L8("[TrackerConnection] HTTP response body chunk received: "));
			HLWRITELN(iLog, dataChunk);
			
			if (iReceiveBuffer)
			{
				HBufC8* temp = HBufC8::NewL(
					iReceiveBuffer->Length() + dataChunk.Length());
				TPtr8 tempPtr(temp->Des());
				tempPtr.Copy(*iReceiveBuffer);
				tempPtr.Append(dataChunk);
				
				delete iReceiveBuffer;
				iReceiveBuffer = temp;
			}
			else
				iReceiveBuffer = dataChunk.AllocL();

			// Always remember to release the body data.
			body->ReleaseData();
		
			// 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)
			{
				
				#ifdef LOG_TO_FILE
				_LIT(KBodyReceived,"Body received");
				HLWRITELN(iLog, KBodyReceived);
				#endif
				
				//CSTBencode* bencodedResponse = CSTBencode::ParseL(*iReceiveBuffer);	
				//iLog->WriteLineL(*iReceiveBuffer);
				//
				//if (bencodedResponse)
				//{
				//	CleanupStack::PushL(bencodedResponse);
				//	iTorrent.ProcessTrackerResponseL(bencodedResponse);
				//	CleanupStack::PopAndDestroy(); // bencodedResponse
				//}
			}
		}
		break;

		case THTTPEvent::EResponseComplete:
		{
			// Indicates that header & body of response is completely received.
			// No further action here needed.
			//_LIT(KTransactionComplete, "Transaction Complete");
			//iLog->WriteLineL(KTransactionComplete);
			//iResult = ESucceeded;
		}
		break;

		case THTTPEvent::ESucceeded:
		{
			LWRITELN(iLog, _L("[Trackerconnection] HTTP transaction succeded"));

			CSTBencode* bencodedResponse = CSTBencode::ParseL(*iReceiveBuffer);	
			//iLog->WriteLineL(*iReceiveBuffer);
			
			if (bencodedResponse && iObserver)
			{
				CleanupStack::PushL(bencodedResponse);
				iObserver->TrackerResponseReceivedL(*bencodedResponse);
				CleanupStack::PopAndDestroy(); // bencodedResponse
			}
			
			iRunning = EFalse;
			
			if (iObserver)
				iObserver->TrackerConnectionSucceededL();
		}
		break;

		case THTTPEvent::EFailed:
		{
			LWRITELN(iLog, _L("[Trackerconnection] HTTP transaction failed"));
			iRunning = EFalse;
			if (iObserver)
				iObserver->TrackerConnectionFailedL();
		}
		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)
			{
				LWRITE(iLog, _L("[Trackerconnection] HTTP transaction failed, "));
				_LIT(KErrorStr, "Error: %d");
				text.Format(KErrorStr, aEvent.iStatus);
				LWRITELN(iLog, text);
			
				// Just close the transaction on errors
				aTransaction.Close();
				iRunning = EFalse;
				
				if (iObserver)
					iObserver->TrackerConnectionFailedL();
			}
			else
			{
				// Other events are not errors (e.g. permanent and temporary
				// redirections)
				_LIT(KUnrecognisedEvent, "[Trackerconnection] Unrecognised event: %d");
				text.Format(KUnrecognisedEvent, aEvent.iStatus);
				LWRITELN(iLog, text);
			}		
		}
		break;
	}
}