利用WinInet下载文件

时间:2021-12-02 09:56:39

  自己写的例子,望路过的高手指点一下这种代码风格有没有什么缺陷,分享一下技巧:

//与网页的交互,从网页下载 (参数1为文件的URL,参数2为下载的文件的绝对路径,包括文件名及文件类型)
BOOL WebMutal(TCHAR *lpDwownURL, TCHAR *SavePath)
{

HINTERNET hInternetOpen = NULL;
HINTERNET hHttpConnect = NULL;
HINTERNET hHttpRequest = NULL;
BYTE *pMessageBody = NULL; // 保存文件的指针
try
{
// 先判断是否联网
if (!::InternetCheckConnection(lpDwownURL, FLAG_ICC_FORCE_CONNECTION, 0))
{
throw 0;
}
// 解析URL以及他的组成部分
TCHAR szHostName[128] = {0};
TCHAR szUrlPath[512] = {0};

URL_COMPONENTS stUrlAnalysis;
ZeroMemory(&stUrlAnalysis, sizeof (URL_COMPONENTS));
stUrlAnalysis.dwStructSize = sizeof(URL_COMPONENTS);
stUrlAnalysis.dwHostNameLength = sizeof(char)*128;
stUrlAnalysis.dwUrlPathLength = sizeof(char)*512;
stUrlAnalysis.lpszHostName = szHostName;
stUrlAnalysis.lpszUrlPath = szUrlPath;

// 解析域名
if(!::InternetCrackUrl(lpDwownURL,0,ICU_ESCAPE,&stUrlAnalysis))
{
throw 0;
}

//初始化WinInet,获取跟句柄
hInternetOpen = ::InternetOpenA(NULL,INTERNET_OPEN_TYPE_DIRECT ,NULL,NULL,0); //INTERNET_OPEN_TYPE_PRECONFIG
if (NULL == hInternetOpen)
{
throw 0;
}

//打开一个HTTP的文件协议
hHttpConnect = ::InternetConnect(hInternetOpen,szHostName,INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,INTERNET_FLAG_PASSIVE,0);
if (NULL == hHttpConnect)
{
throw 0;
}

//打开HTTP请求句柄

hHttpRequest = ::HttpOpenRequest(hHttpConnect,L"GET",szUrlPath,HTTP_VERSION,NULL,NULL,INTERNET_FLAG_NO_UI | INTERNET_FLAG_DONT_CACHE,1);
if (NULL == hHttpRequest)
{
throw 0;
}


if (!::HttpSendRequestA(hHttpRequest, NULL, 0, NULL, NULL)) //向服务器发送这个请求
{
throw 0;
}

// 检查HTTP响应消息的头
DWORD dwInfoBufferLength = 0;
BYTE *pInfoBuffer = NULL;
while (!::HttpQueryInfo(hHttpRequest, HTTP_QUERY_CONTENT_LENGTH, pInfoBuffer, &dwInfoBufferLength, NULL)) //接收服务器返回的信息 (此处我们接收文件的大小)
{
DWORD dwError = GetLastError();
if (dwError == ERROR_INSUFFICIENT_BUFFER) // 传递给参数的缓冲区太小
{
pInfoBuffer = new BYTE[dwInfoBufferLength+1];
}
else
{
throw 0;
}
}
memcpy(&pInfoBuffer[dwInfoBufferLength],"\0",1);

//得到的文件大小转换为int型
unsigned long dwFileSile =_wtoi((WCHAR*)pInfoBuffer);
delete[] pInfoBuffer;
DWORD dwBytesRead=0;
pMessageBody = new BYTE[dwFileSile+1];
if (NULL != pMessageBody)
{
if (!InternetReadFile(hHttpRequest, pMessageBody,dwFileSile, &dwBytesRead))
{
throw 0;
}
}
else
{
throw 0;
}

// 保存文件
HANDLE hFile;
hFile=::CreateFile(SavePath,GENERIC_WRITE|GENERIC_READ ,NULL,NULL,OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL,0); // 打开一个文件,获取文件句柄 设置属性为可读可写
if (NULL == hFile)
{
throw 0;
}
unsigned long Bytes;
if( NULL== WriteFile(hFile,pMessageBody,dwFileSile,&Bytes,NULL)) //向文件写入数据
{
CloseHandle(hFile);
throw 0;
}
CloseHandle(hFile);
delete[] pMessageBody;
}
catch(...)
{
if (NULL != hInternetOpen)
{
::InternetCloseHandle(hInternetOpen);
}
if (NULL != hHttpConnect)
{
::InternetCloseHandle(hHttpConnect);
}
if (NULL != hHttpRequest)
{
::InternetCloseHandle(hHttpRequest);
}
if (NULL != pMessageBody)
{
delete[] pMessageBody;
}
return FALSE;
}
return TRUE;
}