Using CInternetSession to package multithreaded http file downloads

Source: Internet
Author: User
Tags file size

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() ;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.