Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vb.net - How can I get the WebClient to use Cookies?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Here's the C# version of the above code:

using System.Net;
class CookieAwareWebClient : WebClient
{
    private CookieContainer cc = new CookieContainer();
    private string lastPage;

    protected override WebRequest GetWebRequest(System.Uri address)
    {
        WebRequest R = base.GetWebRequest(address);
        if (R is HttpWebRequest)
        {
            HttpWebRequest WR = (HttpWebRequest)R;
            WR.CookieContainer = cc;
            if (lastPage != null)
            {
                WR.Referer = lastPage;
            }
        }
        lastPage = address.ToString();
        return R;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...