如何从代码登录

时间:2011-01-20 19:03:15

标签: c# web autologin

我需要从网站“hh.ua”下载页面来源,但首先我必须登录。我尝试了很多不同的方法,但是登录失败了。该页面的操作源是“http://hh.ua/logon.do”,我试图监控为日志记录发送的查询,它是 - http://hh.ua/logon.do?username=111&password=333&action=%D0%92%D0%BE%D0%B9%D1%82%D0%B8。请帮助!)

这是代码

        string formUrl = "http://hh.ua/logon.do"; 
        string formParams = string.Format("username={0}&password={1}&action=%D0%92%D0%BE%D0%B9%D1%82%D0%B8", "anli_@mail.ru", "80903798516");
        string cookieHeader;
        WebRequest req = WebRequest.Create(formUrl);
        req.ContentType = "application/x-www-form-urlencoded";
        req.Method = "POST";
        byte[] bytes = Encoding.ASCII.GetBytes(formParams);
        req.ContentLength = bytes.Length;
        using (Stream os = req.GetRequestStream())
        {
            os.Write(bytes, 0, bytes.Length);
        }
        WebResponse resp = req.GetResponse();

        cookieHeader = resp.Headers["Set-cookie"];
        return cookieHeader;

        string pageSource;
        string getUrl = "http://hh.ua/resume/ae23733eff00c000df0039ed1f476831706856";
        WebRequest getRequest = WebRequest.Create(getUrl);
        getRequest.Headers.Add("Cookie", cookieHeader);
        WebResponse getResponse = getRequest.GetResponse();
        using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
        {
            pageSource = sr.ReadToEnd();
        }

我知道记录失败,因为下载的页面是登录页面。

2 个答案:

答案 0 :(得分:0)

对于那些涉及大量网络的项目,我发现WatiN非常有用。虽然WatiN可能起源于测试驱动的世界,但它非常适合需要引导网络浏览器的任何东西(现在支持Chrome和Firefox :)。

答案 1 :(得分:0)

您可以使用我在此描述的此技术自动登录:
http://codecube.net/2010/02/reusing-phpbbs-authentication-system/