Home > Uncategorized > Extending WebClient in Visual Basic .NET

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.Net

Public Class CookieAwareWebClient
Inherits WebClient

Private 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 Function

Protected 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 Function

End Class

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: