使用WinInet获取网页

  • 时间:
  • 来源:互联网
  • 文章标签:

参考: 使用WinInet实现http协议

1.VS2015 ANSI

#include "stdafx.h"
//GET 方法
#include <Windows.h>
#include <WinInet.h>
#include <stdio.h>
#pragma comment(lib, "WinInet.lib")
 
int main()
{
	HINTERNET hInternet = InternetOpen("Testing", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);//初始化WinINet
	HINTERNET hConnect = InternetConnectA(hInternet, "baidu.com", INTERNET_DEFAULT_HTTP_PORT,
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);//连接服务器
	HINTERNET hOpenRequest = HttpOpenRequest(hConnect, "GET", "/index.html", NULL, NULL,
		(LPCSTR*)"*/*", INTERNET_FLAG_DONT_CACHE, 1);//创建http请求
	BOOL bRequest = HttpSendRequestA(hOpenRequest, NULL, 0, NULL, 0);//发送http请求
	char szBuffer[1024] = { 0 };
	DWORD dwByteRead = 0;
	FILE* fp = NULL;
	fopen_s(&fp, "1.html", "w");
	while (InternetReadFile(hOpenRequest, szBuffer, sizeof(szBuffer), &dwByteRead) && dwByteRead > 0)
	{
		fwrite(szBuffer, dwByteRead, 1, fp);
		ZeroMemory(szBuffer, dwByteRead);
	}
	fclose(fp);
	return 0;
}

//POST方法

#include <Windows.h>
#include <WinInet.h>
#include <stdio.h>

#pragma comment(lib, "WinInet.lib")

int main()
{
	
	HINTERNET hInternet = InternetOpenA("Testing", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); //初始化WinINet
	char strSever[] = "blog.csdn.net";
	HINTERNET hConnect = InternetConnectA(hInternet, strSever, INTERNET_DEFAULT_HTTP_PORT,
		NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); //连接服务器
	char strObject[] = "/wzx19840423/article/details/6536342";
	HINTERNET hOpenRequest = HttpOpenRequestA(hConnect, "POST", strObject, NULL, NULL,
		(LPCSTR*)"*/*", INTERNET_FLAG_DONT_CACHE, 1); //创建http请求
	//char hdrs[] = "Content-Type: application/x-www-form-urlencoded";
	//char options[] = "/6536342";
	//BOOL bRequest = HttpSendRequestA(hOpenRequest, hdrs, (DWORD)strlen(hdrs), options, (DWORD)strlen(options)); //发送http请求
	BOOL bRequest = HttpSendRequestA(hOpenRequest, NULL, 0, NULL, 0);//发送http请求
	char szBuffer[1024] = { 0 };
	DWORD dwByteRead = 0;
	FILE* fp = NULL;
	fopen_s(&fp, "1.html", "w");
	while (InternetReadFile(hOpenRequest, szBuffer, sizeof(szBuffer), &dwByteRead) && dwByteRead > 0)
	{
		fwrite(szBuffer, dwByteRead, 1, fp);
		ZeroMemory(szBuffer, dwByteRead);
	}
	fclose(fp);
	return 0;
}


本文链接http://www.taodudu.cc/news/show-647728.html