dimanche 28 juin 2015

C# how to Download a file with a cookie(login)

I am trying to login on this website. Currently I'm using this code:

private string Login(string username, string password)
{
    string formUrl = "http://ift.tt/1GIXYXM";
    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"];
}

I always get 1 set-cookie back. When I login to this website with web browser(Chrome) I get back 10 + local storage. I have tried to use CookieCollection as follows:resp.Cookies. But i still got back only one cookie.

The other problem is, that i cant download this file with the cookie I get. I only get back the login page. For downloading i use this function:

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

As I said before I used CookieCollection when I log in, I have also tried CookieContainer in this function like this:

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

What am i doing wrong?

Aucun commentaire:

Enregistrer un commentaire