InternetOpen, InternetOpenUrl, InternetReadFile 获取网页源代码

使用InternetOpen初始化WinINet函数,然后在使用InternetOpenUrl打开指定链接,最后就用InternetReadFile就能读取到网页源代码.

下面的代码能够打开http://www.baidu.com/并且将网页源代码打印出来.

#include <stdio.h>
#include <windows.h>
#include <wininet.h>
#pragma comment(lib,"Wininet.lib")
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
vector<char> v;
CHAR szUrl[] = "http://www.baidu.com/";
CHAR szAgent[] = "";
HINTERNET hInternet1 =
InternetOpen(NULL,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,NULL);
if (NULL == hInternet1)
{
InternetCloseHandle(hInternet1);
return FALSE;
}
HINTERNET hInternet2 =
InternetOpenUrl(hInternet1,szUrl,NULL,NULL,INTERNET_FLAG_NO_CACHE_WRITE,NULL);
if (NULL == hInternet2)
{
InternetCloseHandle(hInternet2);
InternetCloseHandle(hInternet1);
return FALSE;
}
DWORD dwMaxDataLength = 500;
PBYTE pBuf = (PBYTE)malloc(dwMaxDataLength*sizeof(TCHAR));
if (NULL == pBuf)
{
InternetCloseHandle(hInternet2);
InternetCloseHandle(hInternet1);
return FALSE;
}
DWORD dwReadDataLength = NULL;
BOOL bRet = TRUE;
do
{
ZeroMemory(pBuf,dwMaxDataLength*sizeof(TCHAR));
bRet = InternetReadFile(hInternet2,pBuf,dwMaxDataLength,&dwReadDataLength);
for (DWORD dw = 0;dw < dwReadDataLength;dw++)
{
v.push_back(pBuf[dw]);
}
} while (NULL != dwReadDataLength);
vector<char>::iterator i;
for(i=v.begin(); i!=v.end(); i++)
printf("%c",*i);
return 0;
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。