如何让 WebClient 使用 Cookie? [英] How can I get the WebClient to use Cookies?

查看:63
本文介绍了如何让 WebClient 使用 Cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望 VB.net WebClient 记住 cookie.

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

我搜索并尝试了许多重载类.

I have searched and tried numerous overloads classes.

我想通过 POST 登录到一个网站,然后 POST 到另一个页面并获取其内容,同时仍保留我的会话.

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

在不使用 WebBrowser 控件的情况下,这可以通过 VB.net 实现吗?

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

我尝试了 Chilkat.HTTP 并且它有效,但我想使用 .Net 库.

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

推荐答案

创建一个继承自 WebClient 的新类,该类存储 CookieContainer,如@Guffa 所说.这是我使用的代码,它可以做到这一点,并且还可以使引用者保持活动状态:

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

以下是上述代码的 C# 版本:

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;
    }
}

这篇关于如何让 WebClient 使用 Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆