MFC CInternetSession OpenUrl 下载文件 防止异常

	HINTERNET hOpen = InternetOpen (NULL,PRE_CONFIG_INTERNET_ACCESS,NULL,  NULL, 0);
	HINTERNET hRequest = InternetOpenUrl (hOpen, m_theUrl,NULL, 0, INTERNET_FLAG_TRANSFER_BINARY,0);
	if( hOpen )
	{
		InternetCloseHandle(hOpen);
	}
	
	if(!hRequest)return FALSE;
	
	InternetCloseHandle(hRequest);

	CInternetSession session;
	CInternetFile* remoteFile =(CInternetFile*)session.OpenURL(
		m_theUrl,1,
		INTERNET_FLAG_TRANSFER_BINARY|
		INTERNET_FLAG_DONT_CACHE);
	if(!remoteFile)
	{
		remoteFile->Close();
		delete remoteFile;
		session.Close();
		return FALSE;
	}
	DWORD statusCode;
	((CHttpFile *)remoteFile)->QueryInfoStatusCode(statusCode);
	if (statusCode==404)return FALSE;
	
	CFile localFile;//MZ?
	if(localFile.Open(localFilename,CFile::modeCreate|CFile::modeWrite|CFile::typeBinary,NULL))
	{
		int readlen = -1;
		char buf[1024];
		while(1)
		{
			readlen = remoteFile->Read(buf,1024);
			if(readlen == 0)
			{
				break;
			}
			localFile.Write(buf,readlen);
			ZeroMemory(buf,1024);
		}
		localFile.Close();
	}
	
	remoteFile->Close();
	session.Close();
	delete remoteFile;

使用 InternetOpen 和 InternetOpenUrl来判断 Url是否存在

否则直接OpenUlr会造成异常

你可能感兴趣的:(C++)