How do I download an http file? We can, of course, use the socket to implement the HTTP protocol to do, but time-consuming and laborious also easy to bug, for a client-side program stable and easy to maintain is the first, fortunately, Ms for us to provide a powerful Internet API function family, MFC's cinternetsession have some simple encapsulation of them, but such a simple encapsulation is only a semi-finished product for me and other copycat. It has to be processed before it can be eaten.
First, let me introduce the use of CInternetSession:
The following code is the basic way to read a link:
//CInternetSession throws an exception when it encounters some errors, so it must be wrapped up
TRY
{
CInternetSession sess;
Unified binary Download
DWORD dwflag = internet_flag_transfer_binary| internet_flag_dont_cache| Internet_flag_reload;
CHttpFile * PF = (chttpfile*) Sess. OpenURL (strFileName, 1, Dwflag); ASSERT (PF);
if (!PF)
{afxthrowinternetexception (1);}
//Get file size
CString str;
Pf->queryinfo (Http_query_content_length, str);
int nfilesize = _ttoi (str);
char * p = new[nfilesize];
while (true)
{
//per download 8Kb
int n = pf->read (p, (Nfilesize < 8192)? nfilesize:8192) ;
if (n <= 0)
break;
p = n; Nfilesize = n;
}
delete[] p;
Delete PF;
}
Catch_all (e) {}
End_catch_all
This code has a problem, in getting file size this place, for static Web page http_query_content_length query will return the file size, but for asp,php such dynamic Web pages, the query will return 0. You have to accumulate content 1.1 points by calling Chttpfile::getlength, like this:int n = pF->GetLength() ;
while (n)
{
int * p = new BYTE[n] ;
pF->Read (p, n) ;
delete[] p ;
n = pF->GetLength() ;
}