| I l @ ve RuBoard |
The WebClient Class
Why, you might ask, are there two completely different sets of classes for making "Web"
Warning The WebClient class does not provide any support for asynchronous operations.
To get an idea of what the
WebClient
class can do for you, check out the following code example. It
ImportsSystem
ImportsSystem.Net
ImportsSystem.Text
ImportsSystem.IO
ModuleWebClientTest
SubMain()
DimclientAsWebClient=NewWebClient()
DimresStreamAsStream=_
client.OpenRead("http://www.gotdotnet.com/about_new.aspx")
DimsrAsStreamReader=NewStreamReader(resStream)
DimresChar(256)AsChar
DimcharCountAsInteger=sr.Read(resChar,0,resChar.Length)
DoWhilecharCount>0
DimstrAsString=NewString(resChar,0,charCount)
Console.Write(str)
charCount=sr.Read(resChar,0,resChar.Length)
Loop
resStream.Close()
EndSub
EndModule
As I mentioned, internally the
WebClient
class uses both the
WebRequest
and
WebResponse
classes. The
WebClient
exposes methods both for sending and reading data. However, because it is designed to keep things simple, it provides support for synchronous (blocking) calls only. Table 6-1 describes the major
Table 6-1. Selected Methods of the WebClient Class
Apart from the fact that all WebClient method calls are synchronous, other potential disadvantages include:
When you deal with downloads in general, and WebClient in particular, you should be aware of the classes described in Table 6-2. These classes can help your application work through proxy servers and handle authentication and credentials. Table 6-2. Useful Classes for Making Web Requests
Here's a sample that uses some of the other useful methods of the WebClient class. Note the use of the DownloadData and DownloadFile methods.
ImportsSystem
ImportsSystem.Net
ImportsSystem.Text
ImportsSystem.Collections.Specialized
ModuleWebClientSample
PublicSubMain()
Try
DimclientAsNewWebClient()
DimpageDataAsByte()=_
client.DownloadData("http://www.gotdotnet.com")
DimpageHtmlAsString=Encoding.ASCII.GetString(pageData)
Console.WriteLine(pageHtml)
client.DownloadFile("http://www.gotdotnet.com", "C:\Temp.html")
CatchwebExAsWebException
Console.WriteLine(webEx.ToString())
EndTry
Console.WriteLine("Hitanykeytocontinue...")
Console.Read()
EndSub
EndModule
Most of the information about the
WebClient
is pretty much a rehash of the
WebRequest
material, so I won't
|
| I l @ ve RuBoard |