Extending WebClient in Visual Basic .NET
The WebCient class encapsulates away most of the stuff that you would normally do with a HttpWebRequest and HttpWebResponse, but sometimes this ‘simplification’ does tend to hide functionality that would be useful. Luckily you can create a derived class, and access this functionality again, to expose it to your app.
The two key functions that WebClient misses is cookie awareness, i.e. cookes set by the server in one request are persisted to the next request. This is done by overriding the GetWebRequest method and setting a CookieContainer.
The next function was that if a Http request encounters a 301 or 302 redirect, then you don’t know where the server has sent you to. I fixed this by overriding GetWebResponse and setting currentPage as the ResponseUri
And… it’s all in VB.NET
Imports System.Web
Imports System.NetPublic Class CookieAwareWebClient
Inherits WebClientPrivate cc As New CookieContainer()
Private lastPage As String
Public currentPage As Uri
Protected Overrides Function GetWebRequest(ByVal address As System.Uri) As System.Net.WebRequest
Dim R = MyBase.GetWebRequest(address)
If TypeOf R Is HttpWebRequest Then
With DirectCast(R, HttpWebRequest)
.CookieContainer = cc
If Not lastPage Is Nothing Then
.Referer = lastPage
End If
End With
End If
lastPage = address.ToString()
Return R
End FunctionProtected Overrides Function GetWebResponse(request As WebRequest) As WebResponse
Dim R = MyBase.GetWebResponse(request)
If TypeOf R Is HttpWebResponse Then
With DirectCast(R, HttpWebResponse)
currentPage = .ResponseUri
End With
End If
Return R
End FunctionEnd Class