⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 crobotinternet.cpp

📁 beereader source code
💻 CPP
📖 第 1 页 / 共 4 页
字号:
// *                      *
// ************************
// Function: Returns the value for the specified header field.
//			 Call httpHeaderFields before calling this function.
//
// Inputs:	 sFieldName		  - The header field name desired 
//								 (example: "Last-modified").
//			 m_sHeader		  - Set from previous call to 
//								 httpHeaderFields
//			 m_nHeaderFields  - Set from previous call to 
//                               httpHeaderFields
//			 m_sHeaderName[]  - Set from previous call to
//								 httpHeaderFields
//			 m_sHeaderValue[] - Set from previous call to
//								 httpHeaderFields
//
// Outputs:	<function_result> - True if header field was found
//			sValue            - Value for the field

BOOL CRobotInternet::httpGetHeaderField(const CString& sName,
										CString& sValue)
{
	CString sTemp1;
	CString sTemp2;
	sValue = "";
	sTemp1 = sName;
	sTemp1.MakeLower();
	if (sTemp1.Right(1) == ":")
		sTemp1 = sTemp1.Left(sTemp1.GetLength() - 1);
	
	for (int n = 0; n < m_nHeaderFields; n++)
	{
		sTemp2 = m_sHeadName[n];
		sTemp2.MakeLower();
		if (sTemp1 == sTemp2)
		{
			sValue = m_sHeadValue[n];
			n = m_nHeaderFields;
			return true;
			} // End if
	} // End for
	return false;
}


// --------------------------------------------------------------
// ************** public
// *            *
// *  httpPost  *
// *            *
// **************
// Function: Submits a URL and form data/parameters using the POST
//           method. Retrieves a response returns it in CString form.
//
// Inputs:	sURL              - The URL to access
//								 (example: "www.mysite.com")
//			sData			  - The parameters (or "form data")
//								 to submit
//
// Outputs:	<function_result> - True if data was successfully
//								 retrieved, false otherwise
//			sResponse         - The HTML retrieved
//			nResult           - Completion code. 0 = success,
//								 n = error (defined in CRobot.h)
//			sErrMsg           - The error message, if nResult != 0

BOOL CRobotInternet::httpPost(const CString& sUrl,
							  const CString& sData,
							  CString& sResponse,
							  int& nResult, CString& sErrMsg)
{
	CInternetSession* pSession;
	CHttpConnection* pConnection;
	CHttpFile* pHttpFile;
	int nRead;
	LPSTR pBuffer = NULL;
	CString sResult;
	CString sWorkingUrl;
	CString sHeaders = "";
	CString sMsg;
	sErrMsg = "";
	DWORD dwHttpStatus;
	nResult = CROBOT_ERR_SUCCESS;
	TCHAR sTemp[1024];

	try 
	{
		pSession = NULL;
		pConnection = NULL;
		pHttpFile = NULL;
		nRead = 0;
		pBuffer = new char[1024];
		sResult = "";
		sWorkingUrl = sUrl;
		sHeaders = _T("Content-Type: "
					  "application/x-www-form-urlencoded\r\n")
				   + CreateStandardHeader();

		/* Trim URL and add http:// if it contains no 
		   protocol identifier */
		
		sWorkingUrl.TrimLeft();
		sWorkingUrl.TrimRight();
		if (sWorkingUrl.Find(":") == -1) 
		{
			if (sWorkingUrl.Left(1) == "/")
				sWorkingUrl = "http:" + sWorkingUrl;
			else
				sWorkingUrl = "http://" + sWorkingUrl;
		} // End if

		/* Check the URL - must be valid and of the 'http:'
		   service type */
		DWORD dwServiceType;
		CString sServer, sObject;
		unsigned short nPort;
		if (AfxParseURL(sWorkingUrl,
						dwServiceType,
						sServer,
						sObject,
						nPort))
		{
			// URL is valid. Now check service type.
			if (dwServiceType == AFX_INET_SERVICE_HTTP) 
			{
				// Service type is valid (HTTP). Now make connection.
				pSession = new CInternetSession(
										m_sUserAgent,
										1,
										INTERNET_OPEN_TYPE_PRECONFIG);
				pConnection = pSession->GetHttpConnection(sServer,
														  nPort,
														  NULL,
														  NULL);

				pHttpFile = pConnection->OpenRequest(
										CHttpConnection::HTTP_VERB_POST,
										sObject,
										sServer,
										1,
										NULL,
										NULL,
										INTERNET_FLAG_EXISTING_CONNECT
											| INTERNET_FLAG_RELOAD
											| INTERNET_FLAG_DONT_CACHE);
				strcpy (sTemp, sData);
				pHttpFile->SendRequest(sHeaders,
									   sTemp,
									   sData.GetLength());
				if (pHttpFile) /* SendRequest worked */
				{
					// Check the http return code
					if (!pHttpFile->QueryInfoStatusCode(dwHttpStatus))
						dwHttpStatus = 200;

					if (dwHttpStatus >= 400)
					{
						switch(dwHttpStatus)
						{
						case 404:
							nResult = CROBOT_ERR_NOT_FOUND;
							break;
						case 403:
						case 407:
							nResult = CROBOT_ERR_NOT_AUTHORIZED;
							break;
						default:
							nResult = CROBOT_ERR_CONNECTION_FAILED;
							break;
						} // End switch
					} // End if dwHttpStatus
					else /* No error - read response data */
					{
						nResult = CROBOT_ERR_SUCCESS;
						do 
						{
							nRead = pHttpFile->Read(pBuffer, 1023);
							if (nRead != 0) 
							{
								pBuffer[nRead] = 0;
								sResult += pBuffer;
							} // End if
						} while (nRead != 0);
						sResponse = sResult;
					} // End else
				} // End if pHttpFile
				else /* SendRequest failed */
				{
					nResult = CROBOT_ERR_CONNECTION_FAILED;
				} // End else
			} // End if
			else
				// Wrong service
				nResult = CROBOT_ERR_INVALID_URL;
		} // End if
		else
			// Invalid URL
			nResult = CROBOT_ERR_INVALID_URL;
	} // End try

	catch (CInternetException* e) 
	{
		e->Delete();
		sResponse = sResult;
		
		// Exception occurred
		nResult = CROBOT_ERR_CONNECTION_FAILED;
	} // End catch
	catch (...) 
	{
		sResponse = sResult;
		
		// Exception occurred
		nResult = CROBOT_ERR_CONNECTION_FAILED;
	} // End catch

// Clean up and exit function

	if (pBuffer != NULL)
	{
		delete pBuffer;
		pBuffer = NULL;
	} // End if
	
	if (pHttpFile != NULL) 
	{
		pHttpFile->Close();
		delete pHttpFile; 
	} // End if

	if (pConnection != NULL) 
	{
		pConnection->Close();
		delete pConnection; 
	} // End if

	if (pSession != NULL) 
	{
		pSession->Close();
		delete pSession; 
	} // End if
	
	sErrMsg = ErrorMessage(nResult);
	if (nResult == CROBOT_ERR_SUCCESS)
		return true;
	else
		return false;
}


// --------------------------------------------------------------
// ****************** public
// *                *
// *  httpPostFile  *
// *                *
// ******************
// Function: Submits a URL and form data/parameters using
//           the POST method. Retrieves response and outputs
//           it to a file.
//
// Inputs:	sURL              - The URL to access
//								 (example: "www.mysite.com")
//			sData			  - The parameters (or "form data")
//								 to submit
//			sOutputFilespec   - File specification of file to 
//								 create/overwrite
//
// Outputs:	<function_result> - True if data was successfully
//								 retrieved, false otherwise
//			nResult           - Completion code. 0 = success,
//								 n = error (defined in CRobot.h)
//			sErrMsg           - The error message, if nResult != 0

BOOL CRobotInternet::httpPostFile(const CString& sUrl,
								  const CString& sData,
								  const CString& sOutputFilespec,
								  int& nResult,
								  CString& sErrMsg)
{
	CInternetSession* pSession;
	CHttpConnection* pConnection;
	CHttpFile* pHttpFile;
	CString sHeader;
	int nRead;
	LPSTR pBuffer = NULL;
	CString sResult;
	CString sWorkingUrl;
	CString sHeaders = "";
	CFile* pLocalFile;
	char sTemp[1024];
	DWORD dwHttpStatus;
	nResult = CROBOT_ERR_SUCCESS;
	CString sMsg;

	try 
	{
   		pSession = NULL;
		pConnection = NULL;
		pHttpFile = NULL;
		pLocalFile = NULL;
		sHeader = CreateStandardHeader();
		nRead = 0;
		pBuffer = new char[1024];
		sResult = "";
		sWorkingUrl = sUrl;
		sHeaders = _T("Content-Type: "
					  "application/x-www-form-urlencoded\r\n")
				   + CreateStandardHeader();

		/* Trim URL and add http:// if it contains no 
		   protocol identifier */
		
		sWorkingUrl.TrimLeft();
		sWorkingUrl.TrimRight();
		if (sWorkingUrl.Find(":") == -1) 
		{
			if (sWorkingUrl.Left(1) == "/")
				sWorkingUrl = "http:" + sWorkingUrl;
			else
				sWorkingUrl = "http://" + sWorkingUrl;
		} // End if

		/* Check the URL - must be valid and of the 'http:'
		   service type */
		DWORD dwServiceType;
		CString sServer, sObject;
		unsigned short nPort;
		if (AfxParseURL(sWorkingUrl,
						dwServiceType,
						sServer,
						sObject,
						nPort)) 
		{
			// URL is valid. Now check service type.
			if (dwServiceType == AFX_INET_SERVICE_HTTP)
			{
				/* Service type is correct (HTTP). 
				   Now make the connection. */
				pSession = new CInternetSession(
										m_sUserAgent,
										1,
										INTERNET_OPEN_TYPE_PRECONFIG);
				pConnection = pSession->GetHttpConnection(sServer,
														  nPort,
														  NULL,
														  NULL);
				
				pHttpFile = pConnection->OpenRequest(
									CHttpConnection::HTTP_VERB_POST,
									sObject,
									NULL,
									1,
									NULL,
									NULL,
									INTERNET_FLAG_EXISTING_CONNECT
										| INTERNET_FLAG_RELOAD
										| INTERNET_FLAG_DONT_CACHE);

				strcpy (sTemp, sData);
				pHttpFile->SendRequest(sHeaders,
									   &sTemp,
									   sData.GetLength());
				if (pHttpFile) /* SendRequest worked */
				{
					// Check the http return code
					if (!pHttpFile->QueryInfoStatusCode(dwHttpStatus))
						dwHttpStatus = 200;

					if (dwHttpStatus >= 400)
					{
						switch(dwHttpStatus)
						{
						case 404:
							nResult = CROBOT_ERR_NOT_FOUND;
							break;
						case 403:
						case 407:
							nResult = CROBOT_ERR_NOT_AUTHORIZED;
							break;
						default:
							nResult = CROBOT_ERR_CONNECTION_FAILED;
							break;
						} // End switch
					} // End if dwHttpStatus
					else /* No error - read response data */
					{
						nResult = CROBOT_ERR_SUCCESS;
						// Open local file for output
						pLocalFile = new CFile;

						pLocalFile->Open(sOutputFilespec,
										 CFile::modeWrite 
											| CFile::modeCreate);

						do 
						{
							nRead = pHttpFile->Read(pBuffer, 1023);
							if (nRead != 0)
							{
								pBuffer[nRead] = 0;
								pLocalFile->Write(pBuffer, nRead);
							} // End if
						} while (nRead != 0);
					} // End else
				} // End if pHttpFile
				else /* SendRequest failed */
				{
					nResult = CROBOT_ERR_CONNECTION_FAILED;
				}
			} // End if
			else
				// Wrong service
				nResult = CROBOT_ERR_CONNECTION_FAILED;
		} // End if
		else
			// Invalid URL
			nResult = CROBOT_ERR_INVALID_URL;
	} // End try

	catch (CInternetException* e) 
	{
		e->Delete();
		
		// Internet exception occurred
		nResult = CROBOT_ERR_CONNECTION_FAILED;
	} // End catch

	catch (...) 
	{
		// Exception occurred
		nResult = CROBOT_ERR_CONNECTION_FAILED;
	} // End catch

// Clean up and exit function
	
	if (pBuffer != NULL) 
	{
		delete pBuffer; 
		pBuffer = NULL;
	} // End if

	if (pHttpFile != NULL) 
	{
		pHttpFile->Close();
		delete pHttpFile; 
	} // End if
	
	if (pLocalFile != NULL) 
	{
		pLocalFile->Close();
		delete pLocalFile; 
	} // End if

	if (pConnection != NULL) 
	{
		pConnection->Close();
		delete pConnection; 
	} // End if
	
	if (pSession != NULL) 
	{
		pSession->Close();
		delete pSession;
	}  // End if

	sErrMsg = ErrorMessage(nResult);
	if (nResult == CROBOT_ERR_SUCCESS)
		return true;
	else
		return false;
}



// --------------------------------------------------------------
// *************** public
// *             *
// *  httpError  *
// *             *
// ***************
// Function: Scans an HTML response page for HTTP error codes.
//
// Inputs:	sHTML             - HTML response of a prior Internet
//								 access
//
// Outputs:	<function_result> - True if an error code was detected;
//								 false if no errors were detected in
//								 the response
//			nErrorCode        - HTTP error code, such as 404
//			sErrMsg           - Error message text for nErrorCode,
//								 such as "object not found"

BOOL CRobotInternet::httpError(const CString& sHTML,
							   int& nErrorCode,
							   CString& sErrMsg)
{
	CString sTemp = sHTML;
	int nPos;

	nPos = sTemp.Find("HTTP/1.0 ");
	if (nPos != -1)
		sTemp = sTemp.Mid(nPos + 9, 3);

	if (nPos == -1) 
	{
		nPos = sTemp.Find("HTTP Error ");
		if (nPos != -1)
			sTemp = sTemp.Mid(nPos + 11, 3);
	} // End if

	if (nPos != -1) 
	{
		nErrorCode = atoi(sTemp);
		sErrMsg = ResponseMessage(nErrorCode);
		return true;
	} // End if
	else 
	{
		nErrorCode = 0;
		sErrMsg = "";
		return false;
	} // End else
}


// --------------------------------------------------------------
// ************************ public
// *                      *
// *  ParseServerFromURL  *
// *                      *
// ************************
// Function: Scans a URL and returns the server name portion
//           of the URL
//
// Inputs:	sURL              - A fully qualified URL
//
// Outputs:	<function_result> - The server portion of the URL

CString CRobotInternet::ParseServerFromURL(const CString& sURL)
{
	DWORD dwService;
	INTERNET_PORT nPort;
	CString sServer;
	CString sObject;
	CString sPath;
	CString sTempURL;

	sTempURL = sURL;

	if (sTempURL.Find(":") == -1) 
	{
		if (sTempURL.Left(1) != "/")
			sTempURL = "//" + sTempURL;
		sTempURL = "http:" + sTempURL;
	} // End if

	AfxParseURL(sTempURL,
				dwService,
				sServer,
				sObject,
				nPort);

	return sServer;
}


// --------------------------------------------------------------
// ********************** public
// *                    *
// *  ParsePathFromURL  *
// *                    *
// **********************
// Function: Scans a URL and returns the directory path portion of
//           the URL.
//
// Inputs:	sURL              - a fully qualified URL.
//
// Outputs:	<function_result> - the directory path portion of the URL.

CString CRobotInternet::ParsePathFromURL(const CString& sURL)
{
	DWORD dwService;
	INTERNET_PORT nPort;
	CString sServer;
	CString sObject;
	CString sPath;
	int nPos;
	CString sTempURL;

	sTempURL = sURL;

	if (sTempURL.Find(":") == -1) 
	{
		if (sTempURL.Left(1) != "/")
			sTempURL = "//" + sTempURL;
		sTempURL = "http:" + sTempURL;
	} // End if

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -