views:

269

answers:

2

I would like the VB.net WebClient to remember cookies.

I have searched and tried numerous overloads classes.

I want to login to a website via POST, then POST to another page and get its contents whilst still retaining my session.

Is this possible with VB.net without using WebBrowser control ?

I tried Chilkat.HTTP and it works, but I want to use .Net libraries.

Regards, Jeremy.

+1  A: 

You can't make the WebClient class remember the cookies, you have to get the cookie container from the response and use it in the next request.

Guffa
Thanks for the suggestion.
Jeremy Child
+1  A: 

Create a new class the inherits from WebClient that stores the CookieContainer like @Guffa says. Here's code that I use that does that and also keeps the referer alive:

Public Class CookieAwareWebClient
    Inherits WebClient

    Private cc As New CookieContainer()
    Private lastPage As String

    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
End Class
Chris Haas
Will try this. Thankyou. Its similar to the other inherit, then overload classes ive found.
Jeremy Child
I've been using this for years with absolute success. If its not working for you then its not a cookie/session issue but probably the website that you're spidering is using javascript to modify the form-state. If that's the case either check over the javascript or just use a packet monitor or fiddler to see what's actually being sent over the wire.
Chris Haas