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

📄 httpandftptestdlg.cpp

📁 关于wininet用于FTP
💻 CPP
📖 第 1 页 / 共 2 页
字号:
		DWORD	dwTick = GetTickCount();		
		strDownloadUrl = m_URLS.ppszUrls[i];
		strMessage.Format("   The %dth URL:%s",i+1,strDownloadUrl);
		WriteMsgIntoFile(m_strResultFiles,strMessage);
		if (strncmp(strDownloadUrl,"http",4) != 0) 
		{
			WriteMsgIntoFile(m_strResultFiles,"   The URL is not a http_based URL!");
			continue;
		}
		nIndex = strDownloadUrl.ReverseFind('/');
		pszBuf = strDownloadUrl.GetBuffer(strDownloadUrl.GetLength())+nIndex+1;
		strTemp.Format("%s%s",strSavePath,pszBuf);
		// 以下可以封装成一个函数,但是如果要得到文件的大小,要得到修改的日期,必须先OpenUrl.
		CHAR   szHead[] = "Accept: */*\r\n\r\n";
		HINTERNET  hConnect;
		if ( !(hConnect = InternetOpenUrl( m_hSession, strDownloadUrl, szHead,
			 lstrlenA (szHead), INTERNET_FLAG_DONT_CACHE | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_RELOAD |INTERNET_FLAG_EXISTING_CONNECT, 0)))
		{
			DWORD	dwError = GetLastError();
			CString	strTemp;
			strTemp.Format("InternetOpenUrl Error!ErrorCode:%d",dwError);
			AfxMessageBox(strTemp);
			return;
		}
		DWORD dwByteToRead = 0;
		DWORD dwSizeOfRq = 4;
		if (!HttpQueryInfo(hConnect, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, 
				  (LPVOID)&dwByteToRead, &dwSizeOfRq, NULL))
		{
			dwByteToRead = 0;
 		}
		else
		{
			dwTotalLength += dwByteToRead;
		}

		SYSTEMTIME	m_stLastModify;
		dwSizeOfRq = sizeof(SYSTEMTIME);
		if (!HttpQueryInfo(hConnect, HTTP_QUERY_LAST_MODIFIED | HTTP_QUERY_FLAG_SYSTEMTIME, 
					  (LPVOID)&m_stLastModify, &dwSizeOfRq, NULL))
		{
			DWORD	dwError = GetLastError();
			strTemp.Format("Query Modified Error!ErrorCode:%d",dwError);
			AfxMessageBox(strTemp);
		}
 		SYSTEMTIME	systime;
		SystemTimeToTzSpecificLocalTime(NULL,&m_stLastModify,&systime);
		strMessage.Format("   Modified time:%d%d%d  %02d:%02d:%02d",systime.wYear,systime.wMonth,systime.wDay,systime.wHour,systime.wMinute,systime.wSecond);
		WriteMsgIntoFile(m_strResultFiles,strMessage);
		
		UINT	unResult = InternetGetFile(hConnect,strTemp);
		dwTick = GetTickCount() - dwTick;
		strMessage.Format("   File Length : %d\tCosting time : %d\tSpeed\t:%.3f",dwByteToRead,
			dwTick,(float(dwByteToRead))/dwTick);
		WriteMsgIntoFile(m_strResultFiles,strMessage);

		InternetCloseHandle(hConnect);
	}
	dwTotalTime = GetTickCount() -dwTotalTime;
	strMessage.Format("   Total length: %d\tTotal time:%d\tAverage Speed:%.3f",dwTotalLength,
			dwTotalTime,(float(dwTotalLength))/dwTotalTime);
	WriteMsgIntoFile(m_strResultFiles,strMessage);

	WriteMsgIntoFile(m_strResultFiles,"----------------HttpDownload End-----------------\n");
}
void CHttpAndFtpTestDlg::ftpDownload()
{
	CString	strMessage;
	WriteMsgIntoFile(m_strResultFiles,"----------------FtpDownload Strat----------------");	
	CTime time = CTime::GetCurrentTime();
	strMessage = time.Format("%Y%m%d %H:%M:%S ");
	strMessage = "   Start time:" + strMessage;
	WriteMsgIntoFile(m_strResultFiles,strMessage);
	CString	strTemp;
	CString	strDownloadUrl;
	CString	strSavePath;
	strSavePath = m_strSavePath + "FtpDowload\\";
	int	nIndex;
	char	*pszBuf = NULL;
	HINTERNET hFTPSession;
	DWORD	dwTotalTime,dwTotalLength;
	dwTotalTime = GetTickCount();
	dwTotalLength = 0;
	for (int i = 0;i<m_URLS.nUrlNum;i++)
	{
		DWORD	dwTick = GetTickCount();
		strDownloadUrl = m_URLS.ppszUrls[i];
		strMessage.Format("   The %dth URL:%s",i+1,strDownloadUrl);
		WriteMsgIntoFile(m_strResultFiles,strMessage);
		if (strncmp(strDownloadUrl,"ftp",3) != 0) 
		{
			WriteMsgIntoFile(m_strResultFiles,"   The URL is not a ftp_based URL!");
			continue;
		}
		nIndex = strDownloadUrl.ReverseFind('/');
		pszBuf = strDownloadUrl.GetBuffer(strDownloadUrl.GetLength())+nIndex+1;
		// Get the savepath
		strTemp.Format("%s%s",strSavePath,pszBuf);
		char	*pszLoctionServer;
		char	*pszLoctionFilePath;
		int	nStartPos = strDownloadUrl.Find("//");
		CString	strTemp2;
		if (nStartPos != -1)
		{
			pszLoctionServer = strDownloadUrl.GetBuffer(2)+nStartPos+2;
			pszLoctionFilePath = StrChr(pszLoctionServer,'/');
			if (pszLoctionFilePath) 
			{
				*pszLoctionFilePath = '\0';
				pszLoctionFilePath++;
			}
			else
			{
				strTemp2.Format("The %dth URL is Wrong, please check it!",i+1);
				AfxMessageBox(strTemp2);
			}
		}
		else
		{
			strTemp2.Format("The %dth URL is Wrong, please check it!",i+1);
			AfxMessageBox(strTemp2);
		}
		hFTPSession = ::InternetConnect(
					m_hSession,                // Handle from a previous
					pszLoctionServer,		       // Server we wish to connect to.
					INTERNET_DEFAULT_FTP_PORT,    // Use appropriate port.
					NULL,					     // Username, can be NULL.
					NULL,           // Password, can be NULL.
					INTERNET_SERVICE_FTP,            // Flag to use FTP services.
					0,                               // Flags (see SDK docs).
					(DWORD)0);                       // SEE DISCUSSION ON THIS PARAM.
		if (!hFTPSession) {
		DWORD	dwError = GetLastError();
			strTemp2.Format("ConnectError!ErrorCode:%d",dwError);
			AfxMessageBox(strTemp);
			return;
		}
		WIN32_FIND_DATA sWFD;

		HINTERNET 	hFileConnection = ::FtpFindFirstFile(
                    hFTPSession,
                    pszLoctionFilePath,
                    &sWFD,
                    0,
                    0);
		DWORD	dwByteToRead = 0;
		if (hFileConnection)
		{
			dwByteToRead = sWFD.nFileSizeHigh * MAXDWORD + sWFD.nFileSizeLow;
		}
		dwTotalLength += dwByteToRead;
		
		BOOL bResult;
		bResult = ::FtpGetFile(
				hFTPSession,        // Handle from an InternetConnect call
				pszLoctionFilePath,
				strTemp,
				FALSE,
				FILE_ATTRIBUTE_NORMAL,
				FTP_TRANSFER_TYPE_BINARY|INTERNET_FLAG_DONT_CACHE|INTERNET_FLAG_PRAGMA_NOCACHE|INTERNET_FLAG_RELOAD,
				0);
		if (!bResult) {
			DWORD	dwError = GetLastError();
			strTemp.Format("GetFileError!ErrorCode:%d",dwError);
			AfxMessageBox(strTemp);
			InternetCloseHandle(hFTPSession);
			GetDlgItem(IDC_FTP_DOWNLOAD)->EnableWindow(TRUE);
			return;
		}
		InternetCloseHandle(hFTPSession);
		
		dwTick = GetTickCount() - dwTick;
		strMessage.Format("   File Length : %d\tCosting time : %d\tSpeed\t:%.3f",dwByteToRead,
			dwTick,(float(dwByteToRead))/dwTick);
		WriteMsgIntoFile(m_strResultFiles,strMessage);

	}
	
	dwTotalTime = GetTickCount() -dwTotalTime;
	strMessage.Format("   Total length: %d\tTotal time:%d\tAverage Speed:%.3f",dwTotalLength,
			dwTotalTime,(float(dwTotalLength))/dwTotalTime);
	WriteMsgIntoFile(m_strResultFiles,strMessage);

	WriteMsgIntoFile(m_strResultFiles,"----------------FtpDownload End------------------\n");
}

void CHttpAndFtpTestDlg::OnHttpDownload() 
{
	if(bHasRun)return;
	m_nProtocolFlag = 1;
	if (m_strSavePath.GetLength()==0) {
		AfxMessageBox("Your folder is empty!Please Set Folder First!");
	}
	CWinThread*	winThread = AfxBeginThread(ReceiveDataThread,this,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
	winThread->ResumeThread();
}

void CHttpAndFtpTestDlg::OnFtpDownload()
{
	if(bHasRun)return;
	m_nProtocolFlag = 2;
	if (m_strSavePath.GetLength()==0) {
		AfxMessageBox("Your folder is empty!Please Set Folder First!");
	}
	CWinThread*	winThread = AfxBeginThread(ReceiveDataThread,this,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
	winThread->ResumeThread();
}

void CHttpAndFtpTestDlg::OnButtonUrldown() 
{
	if(bHasRun)return;
	m_nProtocolFlag = 0;
	UpdateData(TRUE);
	if (m_strSavePath.GetLength()==0) {
		AfxMessageBox("Your folder is empty!Please Set Folder First!");
	}
	CWinThread*	winThread = AfxBeginThread(ReceiveDataThread,this,THREAD_PRIORITY_NORMAL,0,CREATE_SUSPENDED,NULL);
	winThread->ResumeThread();
}

int CHttpAndFtpTestDlg::GetProtocolFlag()
{
	return	m_nProtocolFlag;
}

CString CHttpAndFtpTestDlg::GetSavePath()
{
	return	m_strSavePath;
}

BOOL CHttpAndFtpTestDlg::InitializeHintnet(HINTERNET* hSession)
{
	DWORD	dwFlags = 1;
	InternetGetConnectedState(&dwFlags, 0);
	if(!(dwFlags & INTERNET_CONNECTION_PROXY))
		*hSession = InternetOpenA("MyAgent", INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY, NULL, NULL, 0);
	else
		*hSession = InternetOpenA("MyAgent", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (*hSession)
		return	TRUE;
	else
		return	FALSE;
}

BOOL CHttpAndFtpTestDlg::GetUrlsFromTxt(LPCSTR szPath)
{
	FILE	*pFileToRead;
	if (!(pFileToRead = fopen(szPath,"rb")))
	{
		CString	strTemp;
		strTemp.Format("%s does not exist!",szPath);
		MessageBox(strTemp);
		return	FALSE;
	}
	fseek(pFileToRead,0,SEEK_END);
	long	lLength = ftell(pFileToRead);
	m_pszFileBuffer = new char[lLength+1];
	m_pszFileBuffer = new char[lLength+1];
	memset(m_pszFileBuffer,0,lLength+1);
	fseek(pFileToRead,0,SEEK_SET);
	fread(m_pszFileBuffer,sizeof(char),lLength,pFileToRead);

	char	*pszSearch,*pszTemp;
	pszTemp = m_pszFileBuffer;
	for (int i= 0;i<500;i++) {
		pszSearch = StrChr(pszTemp,'\r');
		if (pszSearch == NULL) {
			if (strlen(pszTemp)<5) {
				break;
			}
			m_URLS.ppszUrls[i] = pszTemp;
			m_URLS.nUrlNum++;
			break;
		}
		*pszSearch='\0';
		pszSearch=pszSearch+2;
		m_URLS.ppszUrls[i] = pszTemp;
		m_URLS.nUrlNum++;
		pszTemp = pszSearch;
	}
	fclose(pFileToRead);
	return	TRUE;

}



UINT ReceiveDataThread(LPVOID lpParam)
{
	bHasRun = TRUE;
	CHttpAndFtpTestDlg *pDlg = (CHttpAndFtpTestDlg*)lpParam;
	CString	strSavePath = pDlg->GetSavePath();
	int	nflag = pDlg->GetProtocolFlag();

	CString	strTemp;
	DWORD	dwTick = GetTickCount();
	pDlg->GetDlgItem(IDC_STATIC_PROGRESS)->SetWindowText("开始下载!");
	pDlg->GetDlgItem(IDC_STATIC_RESULT)->SetWindowText("");
	
	switch(nflag) {
	case 0:
		pDlg->GetDlgItem(IDC_BUTTON_URLDOWN)->EnableWindow(FALSE);
		pDlg->urlDownload();
		pDlg->GetDlgItem(IDC_BUTTON_URLDOWN)->EnableWindow(TRUE);
		break;
	case 1:
		pDlg->GetDlgItem(IDC_HTTP_DOWNLOAD)->EnableWindow(FALSE);
		pDlg->httpDownload();
		pDlg->GetDlgItem(IDC_HTTP_DOWNLOAD)->EnableWindow(TRUE);
		break;
	default:
		pDlg->GetDlgItem(IDC_FTP_DOWNLOAD)->EnableWindow(FALSE);
		pDlg->ftpDownload();
		pDlg->GetDlgItem(IDC_FTP_DOWNLOAD)->EnableWindow(TRUE);
		break;
	}
	pDlg->GetDlgItem(IDC_STATIC_PROGRESS)->SetWindowText("下载结束!");
	strTemp.Format("耗费时间:%d",GetTickCount()-dwTick);
	pDlg->GetDlgItem(IDC_STATIC_RESULT)->SetWindowText(strTemp);
	bHasRun = FALSE;
	return	TRUE;
}

BOOL CHttpAndFtpTestDlg::CreatSaveDir(LPCSTR szDirectory)
{
	CString	strSavePath;
	strSavePath = m_strSavePath + szDirectory + "\\";
	if((GetFileAttributes(strSavePath)   ==   0xFFFFFFFF))   
	{
		if(!CreateDirectory(strSavePath,   NULL))
		{   
			CString   strError;
			strError.Format("Error:%d\nCant   create   directory   \n",GetLastError());   
			strError+=strSavePath;
			AfxMessageBox(strError);
			return	FALSE;
		}
	}
	return	TRUE;
}

BOOL CHttpAndFtpTestDlg::WriteMsgIntoFile(LPCSTR szFileName,LPCSTR szErrorInfo)
{
	FILE	*file;	
	if (!(file = fopen(szFileName,"a+")))
	{
		return	FALSE;
	}
	fseek(file,0,SEEK_END);
	if (ftell(file)>10*1024*1024) {
		fclose(file);
		return	FALSE;
	}
	fwrite(szErrorInfo,sizeof(char),strlen(szErrorInfo),file);
	fwrite("\n",sizeof(char),1,file);
	fclose(file);
	return	TRUE;
}

BOOL CHttpAndFtpTestDlg::DestroyWindow() 
{
	// TODO: Add your specialized code here and/or call the base class
	if (m_pszFileBuffer) {
		delete	m_pszFileBuffer;
	}
	if (m_URLS.ppszUrls) {
		delete	m_URLS.ppszUrls;
	}
	return CDialog::DestroyWindow();
}

void CHttpAndFtpTestDlg::OnTimer(UINT nIDEvent) 
{
	// TODO: Add your message handler code here and/or call default
	if (nIDEvent == 1253) 
	{
		KillTimer(1253);
		if ((_access(m_strResultFiles,0)==0))
		{
			if (IDYES == MessageBox("The result file is already exist, clean it or not?","Clean Or Not",MB_YESNO))
			{
				fopen(m_strResultFiles,"w");
			}
		}
	}
	CDialog::OnTimer(nIDEvent);
}

void CHttpAndFtpTestDlg::OnButtonShowresult() 
{
	ShellExecute(NULL,"open",m_strResultFiles,NULL,NULL,SW_SHOWNORMAL);
}

void CHttpAndFtpTestDlg::OnButtonHelp() 
{
	if ((_access("help.txt",0)!=0))
	{
		CString	strMessage,strTemp;
		strMessage.Format("\tBefore run this programme,Set a folder for store download files,This folder must exist.\n");
		strTemp.Format("\tAfter that all your download files and result files will stored in this folder.\n");
		strMessage += strTemp;
		strTemp.Format("\tYou will set the urls in the file named \"urlset.txt\".\n");
		strMessage += strTemp;
		strTemp.Format("\tAfter you finish your test,check \"Show Result\" to show the result.\n");
		strMessage += strTemp;
		FILE*	file = fopen("help.txt","w");
		fwrite(strMessage,sizeof(char),strMessage.GetLength(),file);
		fflush(file);
		fclose(file);
	}
	ShellExecute(NULL,"open","help.txt",NULL,NULL,SW_SHOWNORMAL);
}

void CHttpAndFtpTestDlg::OnButtonCreatedownloadfolder() 
{
	UpdateData(TRUE);
	if (GetFileAttributes(m_strSavePath)   ==   0xFFFFFFFF) {
		AfxMessageBox("The folder what you set does not exist!");
		return;
	}
	WritePrivateProfileString("Pubic","SavePath",m_strSavePath,"./HttpandFtptest.ini");
	m_strResultFiles = m_strSavePath+"\\"+"result.txt";
	BOOL	bRet = CreatSaveDir("UrlDowload");
	bRet = bRet && CreatSaveDir("HttpDowload");
	bRet = bRet && CreatSaveDir("FtpDowload");
	if (bRet) {
		AfxMessageBox("Set succeed!");
	}
	
}

⌨️ 快捷键说明

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