C # File Download: WinINet

Source: Internet
Author: User

In C #, in addition to WebClient we can use a set of WindowsAPI to complete the download task. This is the Windows Internet, referred to as WinINet. This paper introduces the basic usage and some practical skills of WinINet through a demo.

Interface Introduction

Compared to WebClient usage, Win32API may be cumbersome to use. So let's start with a brief introduction to the API.

Initialization and release of resources

InternetOpen
This is the first method that needs to be called, it initializes the internal data structure, and prepares for subsequent calls.

InternetCloseHandle
This method is used to close the open Internet handle in use, freeing up resources.

Establish a connection to the server

InternetOpenUrl
This is a general-purpose function that the application can use to request data (as long as the WinINet-supported protocol is available). This interface is especially appropriate when we just want to get the data through a URL that doesn't care about what the communication protocol is about. The method resolves the URL string in the parameter, establishes a connection to the server, and prepares to download the data identified by the RUL.

Check response information

HttpQueryInfo
Retrieves the header information associated with an HTTP request. The main is to see if the request was successful.

Read response content

InternetReadFile
Reads data from a handle opened by the InternetOpenUrl.

Download process

Here we only introduce the download process of the key link, the complete process please refer to the demo of this article.

InternetOpenUrl

When requesting a connection to the server, we focus on three issues: the requested URL, whether the RELOAD identity is used, and whether the client supports gzip compression.

The requested URL does not need to say much, here directly request an HTTP URL.

We don't want to get the data in the client cache, so we want each request to be re-downloaded from the server. You need to pass in the Internet_flag_reload identity for the InternetOpenUrl method.
The vast majority of Web servers currently support gzip compression, and our clients will of course be able to decompress the data returned by the server in gzip format. So we're going to tell the server in the request that the client is able to process the gzip data. Only then will the server proactively return data in gzip format.
The code is as follows:

String referer = "Referer:xxxxxx\naccept-encoding:gzip";//Internet_flag_reload-0x80000000//skips the cache, forcing data to be downloaded from the original server Hinetfile = Nativemethods.internetopenurl (This._hinet, URI. Absoluteuri, Referer, Referer. Length, 0x80000000, IntPtr.Zero);
HttpQueryInfo

Next we begin to examine the information in the header returned by the request that was sent earlier. The main thing is: whether the requested resource exists, how long the returned data is, what the original name of the returned file is, and what format the returned data is compressed in.

We will first check the returned status code to determine whether the request was successful, that is, the return is not 200.

byte[] Content = new Byte[buffersize];int count = Buffersize;int temp = 0; Nativemethods.httpqueryinfo (hinetfile, content, out count, out temp) statuscode = Encoding.Unicode.GetString ( Content, 0, count);

When returned correctly, the statuscode should be "200".
Don't be surprised by the second parameter of HttpQueryInfo, we have to pass in 19 in order to get the requested return status. You can refer to query Onfo Flags.
A similar method can be used to get the length of the returned data, the original file name, and the format of the returned data.

InternetReadFile

Before everything goes well, you can read the data. The method itself is nothing to say, but for the purpose of simplifying the operation, the author has made a simple encapsulation of internetreadfile. Created a class Myinternetreadstream that inherits from Stream. Called InternetReadFile in the overridden Read method, and added a callback method to calculate the download progress and other information. The following is a code summary, please refer to Demo for complete code.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

public override int Read (byte[] buffer, int offset, int count) {int dwnumberofbytestoread = Math.min (buffersize, Count)    ;    int length = 0; Nativemethods.internetreadfile (This._hinetfile, This._localbuffer, dwnumberofbytestoread, out length) Array.Copy (    This._localbuffer, 0, buffer, offset, length);    This._bytesreadcallback (length, this._contentlength); return length;}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Gzip Stream

As we mentioned earlier, the server might return gzip-compressed data, which requires us to check the format of the data first. If the data is in gzip format, it needs to be decompressed. In fact, this is very simple in C #, we just have to create a Myinternetreadstream instance of the GZipStream constructor, create a new instance of GZipStream.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

Private Stream Getinternetstream (IntPtr hinetfile) {//Check data is not gzip format string contentencoding = Mywininet.getcontentenc    Oding (Hinetfile); if (Contentencoding.indexof ("gzip", stringcomparison.ordinalignorecase)! =-1) {return new GZipStream (this.    Forgzipreadstream (Hinetfile), compressionmode.decompress, false); } ...} Private Stream Forgzipreadstream (IntPtr hinetfile) {return new Mywininet.myinternetreadstream (Hinetfile, New mywininet . Myinternetreadstream.bytesreadcallback (this. Bytesreadcallback));}

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;padding:0px;border:none; "/>

As for the calculation of download progress, the implementation of real-time download speed and "C # File Download: WebClient" The implementation is basically the same, please refer to the above, or directly read the demo of this article.


C # File Download: WinINet

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.