IT/프로그래밍 관련

wininet : 웹파일 다운로드 코드

KSI 2011. 10. 17. 18:20

#include <windows.h>
#include <wininet.h>
#pragma comment(lib, "wininet.lib")

void download()
{
	HINTERNET hInternet = InternetOpenA("HTTPFILE", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
	HINTERNET hURL = InternetConnectA(hInternet, "www.gamecodi.com", 80, "", "", INTERNET_SERVICE_HTTP, 0, 0);
	HINTERNET hRequest = HttpOpenRequestA(hURL, "GET", "/top_logo_main.gif", NULL, NULL, NULL, 0, 0);
	BOOL bRet = HttpSendRequest(hRequest, NULL, 0, NULL, 0);
	DWORD dwContentLen = 0;
    DWORD dwBufLen = sizeof(dwContentLen);
    BOOL bRet2 = HttpQueryInfo(
		hRequest,
		HTTP_QUERY_CONTENT_LENGTH|HTTP_QUERY_FLAG_NUMBER,
		(LPVOID)&dwContentLen,
		&dwBufLen,
		0
		);

	FILE* f = NULL;
	fopen_s(&f, "a.png", "w+b");

	CHAR buf[1024*10];
	DWORD dwRecvLen = 0;
	DWORD dwBytesRead = 0;
	while(dwContentLen > dwRecvLen)
	{		
		BOOL bRet3 = InternetReadFile(hRequest, buf, sizeof(buf), &dwBytesRead);
		if(!bRet3 || dwBytesRead == 0)
		{
			DWORD dwErr = GetLastError();
			dwErr = 0;
			break;
		}

		dwRecvLen += dwBytesRead;

		fwrite(buf, 1 , dwBytesRead, f);
		printf_s("size: %10d / %10d (%3.2f)\n", dwRecvLen, dwContentLen, float(dwRecvLen)/float(dwContentLen) * 100.0f);
	}

	fclose(f);

	InternetCloseHandle(hRequest);
	InternetCloseHandle(hURL);
	InternetCloseHandle(hInternet);

	return 0;
}
</wininet.h></windows.h>
 
출처 - http://serverdown.tistory.com/256