持之以恒
分类: C/C++
2010-05-28 15:09:47
#include <Windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet.lib")
#define URL_STRING_TEST ""
void main()
{
URL_COMPONENTS crackedURL;
TCHAR szBuffer[1024];//这里是下载缓冲区大小 1KB大小缓冲写入一次
TCHAR szHostName[128];
TCHAR szUrlPath[256];
ZeroMemory(&crackedURL, sizeof (URL_COMPONENTS));
crackedURL.dwStructSize = sizeof (URL_COMPONENTS);
crackedURL.lpszHostName = szHostName;
crackedURL.dwHostNameLength = sizeof(szHostName);
crackedURL.lpszUrlPath = szUrlPath;
crackedURL.dwUrlPathLength = sizeof(szUrlPath);
InternetCrackUrl(URL_STRING_TEST,(DWORD)strlen(URL_STRING_TEST),0,&crackedURL);
FILE* file = fopen("Onelove.mp3", "wb");
HINTERNET hInt,hConn,hReq;
//启用HTTP协议
hInt = InternetOpen("Microsoft Internet Explorer", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
//建立HTTP连接
hConn = InternetConnect(hInt,crackedURL.lpszHostName,crackedURL.nPort,NULL,NULL,INTERNET_SERVICE_HTTP,0,0);
//创建一个URL请求
hReq = HttpOpenRequest(hConn, "GET", crackedURL.lpszUrlPath, NULL, "", NULL, 0, 0);
char buff[64];
DWORD dwContLen = 0;
DWORD dwLen;
BOOL bResult = FALSE;
DWORD nBytesGet = 0;
BOOL bEnd = FALSE;
DWORD dwRetCode = 0;
DWORD dwSizeOfRq = sizeof(DWORD);
dwSizeOfRq = sizeof(buff);
if (HttpSendRequest(hReq,NULL,0,NULL,0)
&& HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwRetCode, &dwSizeOfRq, NULL)
&& dwRetCode < 400)
{
bResult = TRUE;//true;
}
//查询文件大小
if (HttpQueryInfo(hReq, HTTP_QUERY_CONTENT_LENGTH, &buff, &dwSizeOfRq, NULL))
dwContLen = atol(buff);
INTERNET_BUFFERS BufferIn;
BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
BufferIn.Next = NULL;
BufferIn.lpcszHeader = strHeader.c_str(); // 请求头
BufferIn.dwHeadersLength = strHeader.length();
BufferIn.dwHeadersTotal = 0;
BufferIn.lpvBuffer = NULL;
BufferIn.dwBufferLength = 0;
BufferIn.dwBufferTotal = 1024; // This is the only member used other than dwStructSize
BufferIn.dwOffsetLow = 0;
BufferIn.dwOffsetHigh = 0;
*/
hReq = HttpOpenRequest(hConn, "GET", crackedURL.lpszUrlPath, NULL, "", NULL, 0, 0);
if (HttpSendRequest(hReq,NULL,0,NULL,0)
&& HttpQueryInfo(hReq, HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwRetCode, &dwSizeOfRq, NULL)
&& dwRetCode < 400)
{
bResult = TRUE;//true;
}
bool bTrue = HttpSendRequestExA(hReq,&BufferIn,NULL,NULL,0);
while(TRUE)
{
if (bResult)
{
//开始读取文件
bResult = InternetReadFile(hReq, szBuffer, sizeof(szBuffer), &dwLen);
if (bResult)
{
cout<<"reading ... "<<(nBytesGet*100/dwContLen)<<endl;
nBytesGet += dwLen;
if (dwLen == 0)
{
bEnd = TRUE;
break;
}
fwrite(szBuffer, 1, dwLen, file);
}
}
else //数据接受完毕
{
break;
}
}
fclose(file);
}