WebClient
This downloads files from remote servers. We use the WebClient
type in the System.Net
namespace. We make network requests to Internet sites or other servers with an HTTP address.
In VB.NET programs, WebClient
provides critical functionality for downloading webpages and other files. We can manage headers and test responses.
To start, the WebClient
type is found in the System.Net
namespace. Next, the WebClient
is best used in the scope of a Using-block—this helps resource management.
string
of its key.DownloadData
function which receives the URL parameter and returns a byte
array containing the resource's data.Imports System.Net Module Module1 Sub Main() ' Resource acquisition statement. Using client As New WebClient ' Set one of the headers. client.Headers("User-Agent") = "Mozilla/4.0" ' Download data as byte array. Dim arr() As Byte = client.DownloadData("http://www.example.com/") ' Display result. Console.WriteLine(arr.Length) End Using End Sub End Module5821
Next we set two headers, and then download the data. Then we read one of the response headers. The target website returns a Content-Encoding heading that corresponds.
WebClient
to test the web sites you develop for correctness.Imports System.Net Module Module1 Sub Main() Using client As New WebClient ' Set one of the headers. client.Headers("User-Agent") = "Googlebot/2.1" client.Headers("Accept-Encoding") = "gzip" ' Download data. Dim arr() As Byte = client.DownloadData("http://www.dotnetperls.com/") ' Display result. Console.WriteLine(arr.Length) Console.WriteLine(client.ResponseHeaders("Content-Encoding")) End Using End Sub End Module2092 gzip
We can download a web page as a String
, not a byte
array. Often, strings are more easily used in other parts of your program, making the DownloadString
method more convenient.
DownloadString
function behaves similarly to the DownloadData
function, but instead of a byte
array it returns a String
.Imports System.Net Module Module1 Sub Main() Using client As New WebClient ' Download the web page as a string. Dim value As String = client.DownloadString("http://www.dotnetperls.com/") ' Write the first characters of the result. Console.WriteLine(value.Substring(0, 15)) End Using End Sub End Module<!doctype html>
The WebClient
type provides asynchronous functions. Often, we should prefer another threading construct such as BackgroundWorker
.
WebClient
provides essential functionality for many programs. Many .NET programs use WebClient
extensively for programmatic acquisition of remote resources.