请看下面的代码:
objCookieContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://website.com/login.php?user=xxx&pass=xxx");
request.Method = WebRequestMethods.Http.Get;
request.Timeout = 15000;
request.Proxy = null;
request.CookieContainer = objCookieContainer;
HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create("http://website.com/page.php?link=url");
newRequest.Method = WebRequestMethods.Http.Get;
newRequest.Timeout = 15000;
newRequest.Proxy = null;
newRequest.CookieContainer = objCookieContainer;
HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
string readerRequest = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
response = (HttpWebResponse)newRequest.GetResponse();
string readerNewRequest = new StreamReader(response.GetResponseStream()).ReadToEnd();
在使用 request.GetResponse() 之后,cookie 成功地填充了数据并且它有它的身份验证代码并且 readerRequest 也被填充了,之后我调用了 newRequest.GetResponse() 但 readerNewRequest 是空的,我尝试做很多事情但结果总是一样,我解决这个问题的唯一方法是使用 WebBrowser 对象,我在其中传递 url 并且我能够使用 WebBrowser.DocumentStream 获取内容。
我该如何解决这个问题?
最佳答案
private void button1_Click(object sender, EventArgs e)
{
var objCookieContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://website.com/login.php?user=xxx&pass=xxx");
request.Method = WebRequestMethods.Http.Get;
request.Timeout = 15000;
request.Proxy = null;
request.CookieContainer = objCookieContainer;
HttpWebRequest newRequest = (HttpWebRequest)WebRequest.Create("http://website.com/page.php?link=url");
newRequest.Method = WebRequestMethods.Http.Post;
newRequest.Timeout = 15000;
newRequest.Proxy = null;
HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
//once you read response u need to add all cookie sent in header to the 'objCookieContainer' so that it can be forwarded on second response
foreach (Cookie cookie in response.Cookies)
{
objCookieContainer.Add(cookie);
}
string readerRequest = new StreamReader(response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
//since you have added the cookies, this must response fine now
newRequest.CookieContainer = objCookieContainer;
response = (HttpWebResponse)newRequest.GetResponse();
string readerNewRequest = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
如果您的 .NET 版本低于 4.0,您可能会遇到 CookieContainer 错误:检查 This Link
关于c# - 在 winforms 中使用 HttpWebRequest 传递 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14556654/