vb.net 如何让 WebClient 使用 Cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2825377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the WebClient to use Cookies?
提问by Jeremy
I would like the VB.net WebClient to remember cookies.
我希望 VB.net WebClient 记住 cookie。
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.
我想通过 POST 登录到一个网站,然后 POST 到另一个页面并获取其内容,同时仍然保留我的会话。
Is this possible with VB.net without using WebBrowser control ?
在不使用 WebBrowser 控件的情况下,这可以通过 VB.net 实现吗?
I tried Chilkat.HTTP and it works, but I want to use .Net libraries.
我尝试了 Chilkat.HTTP 并且它有效,但我想使用 .Net 库。
回答by Chris Haas
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:
创建一个继承自 WebClient 的新类,该类存储 CookieContainer,如@Guffa 所说。这是我使用的代码,它可以做到这一点并且还可以使引用者保持活动状态:
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:
这是上述代码的 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;
}
}
回答by Guffa
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.
你不能让 WebClient 类记住 cookie,你必须从响应中获取 cookie 容器并在下一个请求中使用它。