本文介绍了接受WebClient的饼干?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用C# Web客户端实验。我有低于至极代码从网站获取的HTML代码和.txt文件写它。我唯一​​的问题是,一些网站要求您接​​受Cookie,才能使用该网站。什么这导致的,而不是写的真正网站的HTML代码.txt文件时,写入cookie的弹出HTML代码

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.

代码:

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?

推荐答案

用法:

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

您将看到GetWebRequest和GetWebResponse 2覆盖的方法。这些方法可以重写来处理cookie的容器中。

You will see two overridden methods for GetWebRequest and GetWebResponse. These methods can be overridden to handle the cookie container.

这篇关于接受WebClient的饼干?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 06:08