Windows API 下载http文件

打开http链接下载文档流程。

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include 
#include 

//加入连接库
#pragma comment(lib, "wininet.lib")


char * UnicodeToANSI(const wchar_t* str)
{
	char* result;
	int textlen;
	textlen = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
	result = (char *)malloc((textlen + 1)*sizeof(char));
	memset(result, 0, sizeof(char) * (textlen + 1));
	WideCharToMultiByte(CP_ACP, 0, str, -1, result, textlen, NULL, NULL);
	return result;
}

int main(int argc, char* argv[])
{
	printf("Hello World! ");
	BYTE buf[1024];
	TCHAR path[MAX_PATH];
	DWORD num;


	//打开
	HINTERNET  hinet = InternetOpen(_TEXT("Microsoft Internet Explorer"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, INTERNET_INVALID_PORT_NUMBER);

	GetTempPath(MAX_PATH, path);
	_tcscat(path, TEXT("/t.zip"));

	//获取文件句柄
	HINTERNET hurl = InternetOpenUrl(hinet, _TEXT("http://file2.mydrivers.com/display/nvidia_forceware7645.zip"), NULL, 0, INTERNET_FLAG_NEED_FILE, NULL);

	std::string spath;
#ifdef UNICODE
	char * allocpath = UnicodeToANSI(path);
	spath = allocpath;
	free(allocpath);

#else
	spath = path;
#endif
	FILE* i = fopen(spath.c_str(), "wb");
	//从internet下载文件内容
	while (TRUE == InternetReadFile(hurl, buf, 1024, &num) && num > 0)
	{
		fwrite(buf, 1, num, i);
	}
	fclose(i);

	//使用完毕文件句柄和关闭连接
	InternetCloseHandle(hurl);

	InternetCloseHandle(hinet);


	return 0;
}

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