C#使用Cookies的WebRequest
我有一个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(); }
这样的东西应该工作,我使用类似的代码来保存登录cookie:
上述就是C#学习教程:C#使用Cookies的WebRequest分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
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("https://www.url.com/foobar"); request.CookieContainer = myContainer;
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1003244.html