微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vb.net – 如何让WebClient使用Cookie?

我想要VB.net WebClient记住cookie。

我已经搜索并尝试过大量重载类。

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

这是可能的VB.net没有使用Webbrowser控件?

我尝试Chilkat.HTTP,它的工作原理,但我想使用.Net库。

创建一个从WebClient继承的新类,它存储像@Guffa这样的CookieContainer。这里是我使用的代码,它也保持引用者的生存:
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#版本:

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

原文地址:https://www.jb51.cc/vb/256035.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐