根据您提供的评论,我将冒险猜测并说您没有正确地将登录 cookie 添加到您的下一个WebRequest
. 使用对象处理 CookieWebRequest
有点困难,因此我建议使用HttpWebRequest
内置HttpWebResponse
cookie 解析的 cookie。您只需在这里和那里更改几行代码:
构建请求(在您的问题中使用相同的示例)
CookieContainer cookies = new CookieContainer();
// When using HttpWebRequest or HttpWebResponse, you need to cast for it to work properly
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = cookies;
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(Gegevens);
req.ContentLength = bytes.Length;
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
// Cast here as well
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
// Code related to the web response goes in here
}
现在,您的 cookie 信息保存在CookieContainer
对象中。稍后可以在您的代码中重复使用它来验证您的登录。如果不需要,则无需将此 cookie 信息写入磁盘。
使用 cookie 信息构建请求
(与上面几乎相同,但您没有添加 POST 数据,而是使用 GET 请求)
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = cookies; // This is where you add your login cookies to the current request
req.Method = "GET";
using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
{
// Code related to the web response goes here
}
希望这会让你走上正确的轨道:)