C#如何下载带有cookie的文件(登录)

时间:2015-06-28 09:30:13

标签: c# .net networking cookies webrequest

我正在尝试登录this网站。目前我正在使用此代码:

private string Login(string username, string password)
{
    string formUrl = "https://osu.ppy.sh/forum/ucp.php?mode=login";
    string formParams = string.Format("username={0}&password={1}&affiliate-button=Sign%20In", username, password);
    HttpWebRequest req = WebRequest.Create(formUrl) as HttpWebRequest;
    req.ContentType = "application/x-www-form-urlencoded";
    req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36";
    req.Method = "POST";
    req.Referer = formUrl;
    req.AllowAutoRedirect = true;
    req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
    req.CookieContainer = new CookieContainer();
    byte[] bytes = Encoding.ASCII.GetBytes(formParams);
    req.ContentLength = bytes.Length;
    using (Stream reqStream = req.GetRequestStream())
    {
        reqStream.Write(bytes, 0, bytes.Length);
    }
    HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
#if DEBUG
    foreach (Cookie c in resp.Cookies)
        System.Diagnostics.Debug.WriteLine(c.Name + " = " + c.Value);
#endif
    return resp.Headers["set-cookie"];
}

我总是得到1套装饼干。当我使用网络浏览器(Chrome)登录本网站时,我会收到10 +本地存储空间。我尝试使用CookieCollection如下:resp.Cookies。但我仍然只回来了一个饼干。

另一个问题是,我无法使用我获得的cookie下载this文件。我只回到登录页面。 下载我使用此功能:

private void Download(string url, string fileName, string cookies)
    {
        try
        {
            HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
            req.Headers.Add(cookies);
            req.Method = "GET";
            req.Referer = "osu.ppy.sh";
            req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
            using (Stream respStream = resp.GetResponseStream())
            {
                SaveToFile(respStream, fileName); //This reads the stream and writes to file
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

正如我之前所说的,当我登录时使用CookieCollection时,我也在这个函数中尝试过CookieContainer:

req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(cookies)

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的方法来检查cookie有效负载是否以逗号分隔 -

    public void GetAllCookies(HttpWebRequest req, HttpWebResponse resp)
    {
        var cookies = resp.Headers["set-cookie"];

        foreach (var cookie in cookies.Split(','))
        {
            Match match = Regex.Match(cookie, "(.+?)=(.+?);");
            if (match.Captures.Count == 0)
                continue;
            resp.Cookies.Add(
                new Cookie(
                    match.Groups[1].ToString(),
                    match.Groups[2].ToString(),
                    "/",
                    req.Host.Split(':')[0]));
        }
    }