HttpWebRequest 不接受 cookie C#
HttpWebRequest no accepting cookies C#
我在 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,然后重试。联系我们....
我做错了什么?先谢谢你了。
仅供参考,我可以通过浏览器毫无问题地访问网页和登录。当我尝试自动化该过程时出现问题。
听起来您正在与之交谈的 url 正在期待一些特定的 header。尝试将 User-Agent header 设置为 Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0
(默认的 Firefox UserAgent)。
否则,请查看 Firefox 中的请求(打开开发人员工具,然后在按下登录按钮之前切换到 'Network' 选项卡)并查看其他 header 是什么请求有。