总结的VC下面读取网页的几种方式

来源:互联网 发布:java移动端开发 编辑:程序博客网 时间:2024/06/01 09:34

第一种:可以正常读取UTF8的中文网页:

#import "msxml2.dll" using namespace MSXML2;CString fetchUTF8HTMLCode(const char *url){CString respString="";::CoInitialize(NULL);     try {IXMLHTTPRequestPtr xmlrequest; HRESULT hr=xmlrequest.CreateInstance("Msxml2.XMLHTTP");if(!SUCCEEDED(hr)) {AfxMessageBox(_T("无法创建XMLHTTP对象,请检查是否安装了MS XML运行库!")); }xmlrequest->open(_bstr_t("GET"),_bstr_t(url),false); xmlrequest->send();BSTR bstrbody;xmlrequest->get_responseText(&bstrbody); _bstr_t bstrtbody(bstrbody);respString = LPCTSTR(bstrtbody);}catch(...){}return respString;}

第二种,可以正常读取GBK的中文网页
#include <afxinet.h>      //加入CIneternetSession的引用CString fetchGBKHTMLCode(const char *url){ CInternetSession mySession(NULL,0);CHttpFile* myHttpFile=NULL;CStringrespString="";//string myData;char myData[1024];myHttpFile=(CHttpFile*)mySession.OpenURL(url);while(myHttpFile->ReadString(myData,1024)){respString=respString+"\r\n";respString+=myData;}myHttpFile->Close ;mySession.Close ;return CString(respString);}

第三种,也可以正常读取GBK和UTF8的网页并保存到硬盘文件,但有一个问题:GBK网页我可以加个CString返回出来,但UTF8网页写进硬盘正常,如果中间加个cstring返回,则变成乱码,试了很久都不成功,希望各位提点建议。
#define MAXBLOCKSIZE 1024  #include <wininet.h>#pragma comment(lib, "wininet.lib")void fetchHTMLCode(const char *Url, const char *filename)  {      HINTERNET hSession = InternetOpen("zwt", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);      if (hSession != NULL)      {          HINTERNET hURL = InternetOpenUrl(hSession, Url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);          if (hURL != NULL)          {              char *Temp = new char[MAXBLOCKSIZE];char *pBuf;pBuf = Temp;            ULONG Number = 1;            FILE *stream;              if( (stream = fopen(filename, "wb" )) != NULL )            {                while (InternetReadFile(hURL, Temp, MAXBLOCKSIZE - 1, &Number)&&Number > 0)                  {                      fwrite(Temp, sizeof (char), Number , stream);                }                 fclose( stream );              }              InternetCloseHandle(hURL);              hURL = NULL;        }         InternetCloseHandle(hSession);          hSession = NULL;      }}  
这三种都是我这菜鸟网上找了半死才最终找到的,目前还只能在VC6的_MSBC模式(默认模式)下运行,UNICODE下抓取中文网页还是有问题。

各位大神请不吝赐教!

原创粉丝点击