C#如何通过HttpWebRequest调用具有相同cookie的多个POST、GET请求
本文关键字:POST 请求 GET cookie HttpWebRequest 何通过 调用 | 更新日期: 2023-09-27 18:24:35
我的问题是,如何使用C#中的相同身份验证cookie通过HttpWebRequest调用多个请求?我试了很多次,但现在我不知道该怎么做:/
我的代码如下:
var postData = "method=loginFormAccount&args[0][email]=###&args[0][pass]=###&args[0][cache]=37317&args[]=1";
var data = Encoding.ASCII.GetBytes(postData);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("###");
request.CookieContainer = new CookieContainer();
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = true;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
var cookies = new CookieContainer();
cookies.Add(response.Cookies);
System.IO.File.WriteAllText(@desktop + "''post.html", new StreamReader(response.GetResponseStream()).ReadToEnd());
// =================================== END LOGIN ==================================== ''
System.IO.File.WriteAllText(@desktop + "''cookie.html","");
foreach (Cookie cook in response.Cookies)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@desktop + "''cookie.html", true))
{
file.WriteLine(cook.ToString());
}
// Show the string representation of the cookie.
}
HttpWebRequest requestNext = (HttpWebRequest)WebRequest.Create("####");
requestNext.CookieContainer = cookies;
requestNext.Method = "GET";
HttpWebResponse responseNext = (HttpWebResponse)requestNext.GetResponse();
//var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
System.IO.File.WriteAllText(@desktop + "''get.html", new StreamReader(responseNext.GetResponseStream()).ReadToEnd());
我的主要问题是,我得到的cookie是认证前的cookie,所以我必须做一些事情来获得认证后的cookie。
试试这个:
HttpWebRequest requestNext = (HttpWebRequest)WebRequest.Create("####");
requestNext.CookieContainer.Add(cookies);