更新时间:2022-11-16 13:59:05
您需要CookieCollection;在收到登录请求的响应后,您可以从响应中读取cookie.
you need the CookieCollection; after receiving the response from your login request you can read the cookies out of the response.
var cookies = new CookieContainer();
ServicePointManager.Expect100Continue = false;
CookieCollection receivedCookies = new CookieCollection();
try
{
var request = (HttpWebRequest) WebRequest.Create(ServerUrl + "index.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
string postData = "try=&username=someLogin&password=somepass";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
// Get the response.
using (WebResponse response = request.GetResponse())
{
receivedCookies = ((HttpWebResponse) response).Cookies;
Logger.DebugFormat("received {0} cookies", receivedCookies.Count);
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
string responseFromServer = reader.ReadToEnd();
Logger.DebugFormat("response from server after login-post: {0}", responseFromServer);
}
}
}
}
catch (Exception ex)
{
Logger.FatalFormat("there was an exception during login: {0}", ex.Message);
return (int) CreateResult.GenericError;
}
在后续请求期间,您必须始终添加该cookie:
during sub-sequent requests you have to add always that cookie(s):
var request =
(HttpWebRequest)WebRequest.Create(ServerUrl + "index.php?nav=callcenter&sub=ccagents&action=new");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = cookies;
request.CookieContainer.Add(receivedCookies);