/********************************************************
*本函数在MFC下实现GET网页信息,并保存到本地文件
*说明:
*strURL:请求网页的URL
*fileaddr:保存到本地的文件地址
*返回:若成功返回0,否则返回非零值
*******************************************************/
#include <afxinet.h>
int HTTP_GET_DATA(CString strURL, CString fileaddr)
{
CInternetSession session;
CHttpConnection* pHttpConnection = NULL;
CHttpFile *pHttpFile = NULL;
CString strServer, strObject;
INTERNET_PORT wPort;
DWORD dwType;
if(!AfxParseURL(strURL, dwType, strServer, strObject, wPort))
{
return 1;//URL解析错误
}
pHttpConnection = session.GetHttpConnection(strServer, wPort);
pHttpFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_GET, strObject);
pHttpFile->SendRequest();
DWORD dwRet;
pHttpFile->QueryInfoStatusCode(dwRet);
if(dwRet == HTTP_STATUS_OK)
{
CFile file;
file.Open(fileaddr, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyNone, 0);
char *pszBuffer = new char[1024];
UINT nRead = pHttpFile->Read(pszBuffer, 1024);
while (nRead > 0)
{
file.Write(pszBuffer, nRead);
nRead = pHttpFile->Read(pszBuffer, 1024);
}
file.Close();
delete []pszBuffer;
}
if(pHttpFile != NULL)
{
pHttpFile->Close();
delete pHttpFile;
pHttpFile = 0;
}
if(pHttpConnection != NULL)
{
pHttpConnection->Close();
delete pHttpConnection;
pHttpConnection = 0;
}
session.Close();
return 0;
}