VC获取网页内容

来源:互联网 发布:歼20对台湾f16 知乎 编辑:程序博客网 时间:2024/05/09 07:56

下面是codeguru上的一个使用wininet类的例子,它能够从给定的url地址中

获取该文件。



这个例子实现了两个方法:

cstring getwebpage(const cstring& url);

void seterrormessage(cstring s);


getwebpage是主要的方法,后面跟的url地址必须是一个完整的url地址,

比如http://www.baidu.com

seterrormessage方法, 能够处理程序中发生的错误。

 在VC中创建一个类cwebworld

// cwebworld.h: interface for the cwebworld class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_CWEBWORLD_H__7A9E56E1_0168_4CBF_A6BF_3FDFE5B88A73__INCLUDED_)
#define AFX_CWEBWORLD_H__7A9E56E1_0168_4CBF_A6BF_3FDFE5B88A73__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "wininet.h"
class cwebworld 
{
public:
 cwebworld();
 virtual ~cwebworld();
 
 void seterrormessage(CString s);
 CString getwebpage(const CString &url);

private:
 CString m_errormessage;
 HINTERNET m_session;//声明一个http链接句柄

};

#endif // !defined(AFX_CWEBWORLD_H__7A9E56E1_0168_4CBF_A6BF_3FDFE5B88A73__INCLUDED_)

 

 

 

// cwebworld.cpp: implementation of the cwebworld class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "web.h"
#include "cwebworld.h"
#include <BASETSD.H>
//#include "WebThief.h"
#pragma   comment(lib, "Wininet.lib ")


#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#define agent_name "codegurubrowser1.0"


cwebworld::cwebworld()
{
 DWORD dwerror;
 // initialize the win32 internet functions
 // 构造函数中初始化网络连接
 m_session = ::InternetOpen(agent_name,INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
 
 dwerror = GetLastError();
}

cwebworld::~cwebworld()
{
 //closeing the session
 //虚拟函数中释放连接
 ::InternetCloseHandle(m_session);
}
CString cwebworld::getwebpage(const CString &url)
{
 HINTERNET hHttpFile;
 char szSizeBuffer[32] = {0};
 DWORD dwLengthSizeBuffer = sizeof(szSizeBuffer);
 DWORD dwFileSize;
 DWORD dwBytesRead;
 bool bSuccessful;
 CString contents;

 //设置莫阿人错误信息
 contents = m_errormessage;

 //打开url并获取http文件句柄
 hHttpFile = InternetOpenUrl(m_session,(const char *)url,NULL,0,0,0);

 if (hHttpFile)
 {
  //获取文件大小
  bool bquery = ::HttpQueryInfo(hHttpFile,HTTP_QUERY_CONTENT_LENGTH,szSizeBuffer,&dwLengthSizeBuffer,NULL);

  if (bquery)
  {
   //计算本地内存空间大小
   dwFileSize = atol(szSizeBuffer);
   LPSTR szContents = contents.GetBuffer(dwFileSize);

   //读取http文件
   bool bread = ::InternetReadFile(hHttpFile,szContents,dwFileSize,&dwBytesRead);

   if (bread)
   {
    bSuccessful = true;
   }
   ::InternetCloseHandle(hHttpFile);
  }
  
 }
 else
 {
  bSuccessful = false; 
 }
 return contents;
}
void cwebworld::seterrormessage(CString s)
{
 m_errormessage = s;
}