我有一个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;
}
但它会尝试登录。如何通过此+许多其他Web请求使用上一次登录请求中的Cookie?
感谢您的帮助。
编辑:
我把它添加到我的代码中,它应该像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();
}
答案 0 :(得分:21)
这样的东西应该可行,我使用类似的代码来保存登录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;