c# WebRequest 使用 WebBrowser cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/650536/
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
c# WebRequest using WebBrowser cookie
提问by madman
I am logging into a site using a WebBrowser, then i want use regex to get some data , but webRequest didnt use web Browse cookie ,
我正在使用 WebBrowser 登录一个站点,然后我想使用正则表达式来获取一些数据,但是 webRequest 没有使用 Web 浏览 cookie,
my webBrowser is in public , is there any way to using WebBrowser cookie in webRequest ?
我的 webBrowser 是公开的,有没有办法在 webRequest 中使用 WebBrowser cookie?
回答by TalkingCode
You can use a CookieContainer for a Webrequest.
您可以将 CookieContainer 用于 Web 请求。
web_cookies = new CookieContainer();
// Create a 'WebRequest' object with the specified url.
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(url);
myWebRequest.CookieContainer = web_cookies;
Hope this helps.
希望这可以帮助。
Ok, you want to do a log in. Thats is different story. You can use NetworkCredential for that.
好的,你想登录。那是另一回事。您可以为此使用 NetworkCredential。
public string get_secure_webpage(string url, string username, string password)
{
WebRequest myWebRequest = WebRequest.Create(url);
NetworkCredential networkCredential = new NetworkCredential(username, password);
myWebRequest.Credentials = networkCredential;
...
...
回答by Jakub
public CookieContainer GetCookieContainer()
{
CookieContainer container = new CookieContainer();
foreach (string cookie in webBrowser1.Document.Cookie.Split(';'))
{
string name = cookie.Split('=')[0];
string value = cookie.Substring(name.Length + 1);
string path = "/";
string domain = ".google.com"; //change to your domain name
container.Add(new Cookie(name.Trim(), value.Trim(), path, domain));
}
return container;
}
This will work on most sites, however sites that use subdomains might be a problem.
这适用于大多数站点,但是使用子域的站点可能会出现问题。
回答by Chris DaMour
is this silverlight? if so, since silverlight 3 if you use the browser network stack than you should get cookies for free. By default you get the browser stack when you create n HttpWebrequest using the WebRequest.Create() method. note if you use CreateHTTP method, you get a client stack, which does not include browser cookies by default (you have to do trickery to get them, as described previously)
这是银光吗?如果是这样,从 Silverlight 3 开始,如果您使用浏览器网络堆栈,那么您应该免费获得 cookie。默认情况下,当您使用 WebRequest.Create() 方法创建 n HttpWebrequest 时,您将获得浏览器堆栈。请注意,如果您使用 CreateHTTP 方法,您将获得一个客户端堆栈,默认情况下该堆栈不包含浏览器 cookie(您必须使用技巧才能获取它们,如前所述)
see http://msdn.microsoft.com/en-us/library/dd920295(VS.95).aspxabout the network stacks in silverlight since version 3
请参阅http://msdn.microsoft.com/en-us/library/dd920295(VS.95).aspx关于自版本 3 以来 Silverlight 中的网络堆栈