针对PickupHockey.com的HttpWebRequest

时间:2015-10-09 05:22:09

标签: asp.net web

我的第一个刮刀在我的曲棍球池的登录页面上进行了验证时遇到了麻烦(只是希望每晚抓一次统计数据以便以更好的格式发布)。

        //my variables
        string userName = "My Pool";
        string password = "hockey";

        ASCIIEncoding encoding = new ASCIIEncoding();
        string postData = "ctl00$MainContent$txtPoolName=" + userName + "&ctl00$MainContent$txtPassword=" + password;
        byte[] postDataBytes = encoding.GetBytes(postData);

        string url = "http://www.pickuphockey.com/hp/hp_login.aspx";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.Headers.Add("Cache-Control: max-age=0");
        request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
        request.Headers.Add("Accept-Encoding: gzip,deflate");
        request.Headers.Add("Accept-Language: en-GB,en-US;q=0.8,en;q=0.6");
        request.Headers.Add("Upgrade-Insecure-Requests: 1");
        request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
        request.ContentLength = postDataBytes.Length;
        request.ContentType = "application/x-www-form-urlencoded";
        request.Headers.Add("Origin: http://www.pickuphockey.com");
        request.Referer = "http://www.pickuphockey.com/hp/hp_login.aspx";
        request.Host = "www.pickuphockey.com";
        request.AllowAutoRedirect = false;

        request.CookieContainer = new CookieContainer();

        using (var stream = request.GetRequestStream())
        {
            stream.Write(postDataBytes, 0, postDataBytes.Length);
            stream.Close();
        }

        //cookie container to save for the next request
        var cookieContainer = new CookieContainer();

        //get the cookies from the login page
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            foreach (Cookie cookie in response.Cookies)
            {
                cookieContainer.Add(cookie);
            }
            Stream receiveStream = response.GetResponseStream();
            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
            var r = readStream.ReadToEnd();
        }

我一直在使用Stack Overflow中的各种示例,并使用fiddler来分析所做的网络通话;尝试将浏览器登录中的所有标题与我正在添加到我的代码中的标题进行匹配。

现在当我编码中断并查看变量r时,我看到一个页面的html说我需要输入用户名/密码的值。我认为这意味着我没有在此调用中正确设置参数,但我读过或调整的任何内容似乎都没有通过此错误。我已经掩盖了我的实际用户/密码,但我认为即使是不正确的值(如果有人尝试代码)也会导致出现错误消息,说明密码错误。任何网络电话专家都可以发现我做错了什么?

一旦代码工作,我会把它包装成一个更好的助手类,我知道现在有点乱。

感谢时间。

1 个答案:

答案 0 :(得分:0)

我终于发现了我的参数字符串的问题,需要根据我尝试访问的确切页面登录页面进行格式化。

        string postData = "txtPoolName=" + userName + "&txtPasswordTemp=" + password + "&txtPassword=" + password + "&Submit2=Go";

当我手动成功登录时,我通过Chrome网络流量检查员了解了这一部分。