HttpWebRequest不接受cookie C#

时间:2015-02-03 23:15:35

标签: c# asp.net cookies httpwebrequest

我遇到HttpWebRequest接受cookie的问题,这是我的代码:

        HttpWebRequest req= (HttpWebRequest)WebRequest.Create("https://www.companyabc.com/security?action=authenticate");
        req.CookieContainer = new CookieContainer();
        req.CookieContainer.Add(new Uri("https://www.companyabc.com"), new CookieCollection());
        string postData = "account_id=xxxx&password=xxxx";
        req.KeepAlive = true;

        byte[] send = Encoding.Default.GetBytes(postData);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = send.Length;

        Stream sout = req.GetRequestStream();
        sout.Write(send, 0, send.Length);
        sout.Flush();
        sout.Close();

我得到的回应是:

对不起... 我们检测到您的浏览器未设置为允许会话Cookie。我们的平台使用Cookie来帮助您改善整体用户体验。没有它们就无法登录。 请启用会话Cookie,然后重试。联系我们....

我做错了什么?先谢谢你。

仅供参考,我可以访问网页并登录,而不会出现任何浏览器问题。当我尝试自动化这个过程时会出现问题。

1 个答案:

答案 0 :(得分:0)

听起来你正在谈论的网址是期待一些特定的标题。尝试将User-Agent标头设置为Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0(默认的Firefox UserAgent)。

如果不这样做,请查看Firefox中的请求(打开开发人员工具,然后在按下登录按钮之前切换到“网络”标签)并查看请求的其他标题。