C# 在 WebClient 中接受 Cookies?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14551345/
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
Accept Cookies in WebClient?
提问by MeesterPatat
I just started experimenting with C# WebClient
. What I have is the code below wich gets html code from a website and writes it in a .txt file. The only problem I have is that some websites require you to accept cookies before you can use the website. What this causes is instead of writing the real website html code to the .txt file, it writes the cookie popup html code.
我刚开始尝试 C# WebClient
。我所拥有的是下面的代码,它从网站获取 html 代码并将其写入 .txt 文件。我遇到的唯一问题是某些网站要求您在使用该网站之前接受 cookie。这导致不是将真正的网站 html 代码写入 .txt 文件,而是写入 cookie 弹出 html 代码。
Code:
代码:
string downloadedString;
System.Net.WebClient client;
client = new System.Net.WebClient();
//"http://nl.wikipedia.org/wiki/Lijst_van_spelers_van_het_Nederlands_voetbalelftal"
downloadedString = client.DownloadString(textBox1.Text);
using (StreamWriter write = new StreamWriter("Data.txt"))
{
write.Write(downloadedString);
}
So what is the solution to this? Can somebody direct me to the right path?
那么解决这个问题的方法是什么?有人可以指引我走正确的道路吗?
回答by maelstrom
This may be a close duplicate of How can I get the WebClient to use Cookies?
这可能是How can I get the WebClient to use Cookies?
The question I referenced above is for VB.NET, but the mechanism should be the same for C#. I suspect the behavior you are seeing is the web-site is sending a cookie and then requesting it back, but your client is not setup to return the cookie to the server, so it interprets that as you 'not accepting cookies.'
我上面提到的问题是针对VB.NET的,但是C#的机制应该是一样的。我怀疑您看到的行为是网站正在发送 cookie 然后请求返回,但是您的客户端没有设置为将 cookie 返回到服务器,因此它会将其解释为您“不接受 cookie”。
Have you used a analysis tool like Fiddler to analyze what is being communicated to/from your client?
您是否使用过 Fiddler 之类的分析工具来分析与您的客户进行交流的内容?
You may also have to send a particular HTTP header to indicate you accept cookies, but I don't recall that being required in my past experience.
您可能还需要发送一个特定的 HTTP 标头来表明您接受 cookie,但我不记得在我过去的经验中是必需的。
回答by Parimal Raj
Usage :
用法 :
CookieContainer cookieJar = new CookieContainer();
cookieJar.Add(new Cookie("my_cookie", "cookie_value", "/", "mysite"));
CookieAwareWebClient client = new CookieAwareWebClient(cookieJar);
string response = client.DownloadString("http://example.com/response_with_cookie_only.php");
public class CookieAwareWebClient : WebClient
{
public CookieContainer CookieContainer { get; set; }
public Uri Uri { get; set; }
public CookieAwareWebClient()
: this(new CookieContainer())
{
}
public CookieAwareWebClient(CookieContainer cookies)
{
this.CookieContainer = cookies;
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
(request as HttpWebRequest).CookieContainer = this.CookieContainer;
}
HttpWebRequest httpRequest = (HttpWebRequest)request;
httpRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
return httpRequest;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
String setCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
//do something if needed to parse out the cookie.
if (setCookieHeader != null)
{
Cookie cookie = new Cookie(); //create cookie
this.CookieContainer.Add(cookie);
}
return response;
}
}
You will see two overridden methods for GetWebRequest and GetWebResponse. These methods can be overridden to handle the cookie container.
您将看到 GetWebRequest 和 GetWebResponse 的两个覆盖方法。可以重写这些方法来处理 cookie 容器。
回答by DenisPashkov
Just store cookie string from headers into your local session _cookies string
只需将标题中的 cookie 字符串存储到本地会话 _cookies 字符串中
if (System.Web.HttpContext.Current.Session["cookie"] != null)
_cookies = System.Web.HttpContext.Current.Session["cookie"].ToString();
using (WebClient wc = new WebClient())
{
wc.Headers.Add("Cookie", _cookies);
string HtmlResult = wc.UploadString(bridge_url, myParameters);
_cookies = wc.ResponseHeaders["Set-Cookie"];
Debug.WriteLine("Headers" + _cookies);
System.Web.HttpContext.Current.Session["cookie"] = _cookies;
}