gpt4 book ai didi

使用 Cookie 的 C# WebRequest

转载 作者:太空狗 更新时间:2023-10-29 17:34:36 27 4
gpt4 key购买 nike

我有一个我一直在开发的 winforms 应用程序,它对消费者帐户运行多个测试。测试需要一次性登录才能执行。

string paramaters = "authmethod=on&chkRememberMe=on&login-form-type=pwd&password=" + pw.Text + "&userid=" + uid.Text + "&username=" + uid.Text;
string strResponse;
HttpWebRequest requestLogin = (HttpWebRequest)WebRequest.Create("https://www.url.com/login.form");
requestLogin.Method = "POST";
requestLogin.CookieContainer = cookieJar;
requestLogin.ContentType = "application/x-www-form-urlencoded";

requestLogin.ContentLength = paramaters.Length;
StreamWriter stOut = new StreamWriter(requestLogin.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(paramaters);
stOut.Close();

StreamReader stIn = new StreamReader(requestLogin.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();

此脚本适用于登录,问题是当我需要实际运行测试时,我需要将所有结果返回到一个字符串中(HTML 结果)。

private string runTestRequest(Uri url, string parameters)
{
string testResults = string.Empty;
HttpWebRequest runTest = (HttpWebRequest)WebRequest.Create(url);
runTest.CookieContainer = cookieJar;
runTest.Method = "POST";
runTest.ContentType = "application/x-www-form-urlencoded";
StreamWriter stOut = new StreamWriter(runTest.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(parameters);
stOut.Close();
StreamReader stIn = new StreamReader(runTest.GetResponse().GetResponseStream());
testResults = stIn.ReadToEnd();
stIn.Close();
return testResults;
}

但是它会尝试登录。我如何将之前登录请求中的 Cookie 与此以及许多其他 Web 请求一起使用?

感谢您的帮助。

编辑:

我将它添加到我的代码中,但它应该做与 BrokenGlass 所说的相同的事情,只是有点不同但仍然不起作用。

foreach (Cookie cookie in responseLogin.Cookies)
{
cookieJar.Add(new Cookie(cookie.Name.Trim(), cookie.Value.Trim(), cookie.Path, cookie.Domain));
richTextBox2.Text += cookie.Name.ToString() + Environment.NewLine + cookie.Value.ToString() + Environment.NewLine + cookie.Path.ToString() + Environment.NewLine + cookie.Domain.ToString();
}

最佳答案

这样的事情应该可行,我正在使用类似的代码来保存登录 cookie:

HttpWebRequest runTest;
//...do login request
//get cookies from response

CookieContainer myContainer = new CookieContainer();
for (int i = 0; i < Response.Cookies.Count; i++)
{
HttpCookie http_cookie = Request.Cookies[i];
Cookie cookie = new Cookie(http_cookie.Name, http_cookie.Value, http_cookie.Path);
myContainer.Add(new Uri(Request.Url.ToString()), cookie);
}

//later:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.url.com/foobar");
request.CookieContainer = myContainer;

关于使用 Cookie 的 C# WebRequest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4158448/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com