超时请求失败

时间:2013-05-06 17:33:01

标签: c# .net httpwebrequest httprequest httpwebresponse

我正致力于在一个特定网站上实现投票过程的自动化。 我的程序需要做以下事情:登录网站,投票给特定的音乐家,然后注销。我使用HttpWebRequest类来执行所有请求。我成功通过授权和投票,但我无法正常注销。我的简单GET请求使我的控制台应用程序挂起一段时间,之后它会因响应超时异常而崩溃。

所以,这就是我所拥有的 - 在浏览器中模拟的注销请求:

Log out request in FireBug Log out request with details

这是我的代码:

private static void Vote(string email, string password)
        {
            // log in

            HttpClient connectionService = new HttpClient();
            connectionService.ContentType = HttpClient.REQUEST_FORM_URLENCODED_TYPE;
            CookieContainer cookies = new CookieContainer();
            string logInParams = String.Format("uname={0}&upass={1}&l=ru", email, password);
            Uri logInRequestUri = new Uri(loginHost);
            var logInResponse = connectionService.DoPost(logInRequestUri, logInParams, cookies);

            // take cookies and pass them to the next request
            if (logInResponse.StatusCode == HttpStatusCode.OK)
            {
                // vote

                string voteParams = String.Format("nid={0}&l=ru", voteID);
                Uri voteRequestUri = new Uri(voteHost);
                var voteResponse = connectionService.DoPost(voteRequestUri, voteParams, cookies);

                // Until this moment everything works fine
                // log out

                Uri logOutUri = new Uri(logoutHost);

                // The commented part below does did not work. I replaced it with a
                // "fresh" request, created from scratch

                //connectionService.ContentType = "text/html";
                //var logOutResponse = connectionService.DoGet(logOutUri, cookies);

                var logOutReq = (HttpWebRequest) WebRequest.Create(logOutUri);
                logOutReq.KeepAlive = true;
                logOutReq.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                logOutReq.Host = "thebestcity.ua";
                logOutReq.Referer = "http://thebestcity.ua/competition/";
                logOutReq.Method = WebRequestMethods.Http.Get;
                logOutReq.CookieContainer = cookies;

                var logOutResponse = logOutReq.GetResponse();

            }
        }

我试图摆脱旧的Cookie并尝试使用 keep-alive AllowAutoRedirect 参数以及内容类型的不同值。似乎没有什么对我有用。应用程序会根据请求挂起,并在超时时失败。

你知道吗,问题是什么?

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。我在每个请求中添加了以下参数:

request.KeepAlive = true;

此外,我已将注销请求的Content-type设置为null:

connectionService.ContentType = null;
var logOutResponse = connectionService.DoGet(logOutUri, cookies);

现在一切正常。