Sunday, January 6, 2008

.NET Reference Guide > WebClient

InformIT: .NET Reference Guide - WebClient - Getting a Page the Easy Way

1.)
Imports System.IO
Imports System.NET

Sub getPage()
’ Create a WebClient instance
Dim myClient As New WebClient()
’ Open the page and get the response as a stream
Dim response As Stream = myClient.OpenRead("http://blog.mischel.com")
’ read the response into a string and show the result
Dim sr As New StreamReader(response)
Dim s As String = sr.ReadToEnd()
Console.WriteLine(s)
sr.Close()
response.Close()
End Sub

2.)
Sub getImage()
’ Create a WebClient instance
Dim myClient As New WebClient()
’ Open the page and get the response into a byte buffer
Dim buffer As Byte() = myClient.DownloadData("http://www.mischel.com/diary/2002/09/charlie9.jpg")
’ Open a file and output the data
Dim fs As New FileStream("charlie9.jpg", FileMode.Create)
fs.Write(buffer, 0, buffer.Length)
fs.Close()
End Sub

3.)
Sub getBigFile()
’ Create a WebClient instance
Dim myClient As New WebClient()
’ Open a stream that references the page
Dim response As Stream = myClient.OpenRead("http://www.mischel.com/diary/2002/09/charlie9.jpg")
Dim fs As New FileStream("charlie9.jpg", FileMode.Create)
Dim buffer(1024) As Byte
Dim bytesRead As Integer = -1
While (bytesRead <> 0)
bytesRead = response.Read(buffer, 0, buffer.Length)
Console.WriteLine("{0} bytes read", bytesRead)
If (bytesRead > 0) Then
fs.Write(buffer, 0, bytesRead)
End If
End While
fs.Close()
response.Close()
End Sub

4.)
client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)")

5.)
X-Pingback = http://blog.mischel.com/xmlrpc.php
Keep-Alive = timeout=5, max=150
Connection = Keep-Alive
Transfer-Encoding = chunked
Content-Type = text/html; charset=UTF-8
Date = Tue, 06 Mar 2007 17:04:07 GMT
Server = Apache Webserver
X-Powered-By = PHP/4.4.4

6.)
’ show the response headers
Dim headers As WebHeaderCollection = myClient.ResponseHeaders
Console.WriteLine("Response headers:")
Dim i As Integer
For i = 0 To headers.Count - 1
Console.WriteLine("{0} = {1}", headers.GetKey(i), headers.Get(i))
Next