使用VC下载内容

C#里有一个WebClient.DownloadData可以用来下载指定网址的内容,

在VC里一样有这样的功能。代码实现很简单,如下:

#include<wininet.h> #pragma comment(lib,"wininet.lib") void CTAXGDlg::downLoadData(void) { DWORD length=0; BYTE buffer[1024]; memset(buffer,0,1024); HINTERNET hInternet; hInternet=InternetOpen(_T("Testing"),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0); if (hInternet==NULL) { //cout<<_T("Internet open failed!")<<endl; return; } HINTERNET hUrl; hUrl=InternetOpenUrl(hInternet,_T("http://www.google.cn/images/isr_g.png"),NULL,0,INTERNET_FLAG_RELOAD,0); if (hUrl==NULL) { // cout<<_T("Internet open url failed!")<<endl; InternetCloseHandle(hInternet); return; } BOOL hwrite; DWORD written; HANDLE hFile; hFile=CreateFile(_T("d://sss.jpg"),GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); if (hFile==INVALID_HANDLE_VALUE) { //cout<<_T("Create File failed!")<<endl; InternetCloseHandle(hUrl); InternetCloseHandle(hInternet); return; } BOOL read; while(1) { read=InternetReadFile(hUrl,buffer,sizeof(buffer),&length); if(length==0) break; hwrite=WriteFile(hFile,buffer,sizeof(buffer),&written,NULL); if (hwrite==0) { //cout<<_T("Write to file failed!")<<endl; CloseHandle(hFile); InternetCloseHandle(hUrl); InternetCloseHandle(hInternet); return; } } CloseHandle(hFile); InternetCloseHandle(hUrl); InternetCloseHandle(hInternet); } 

代码很好,很强大!

你可能感兴趣的:(使用VC下载内容)