日期:2014-05-18  浏览次数:20936 次

C# winform程序 HttpWebRequest 登陆网站,如何保留session再转到其他页面取数据?
我想用C#做个模拟登陆网站的功能,登陆网站有个登陆页面check.php,它用来判断登陆信息,如果正确,就转向index.php,而index.php有session判断,但是前一个页面的session传不过去,怎样才能传过去呢,需要把上一个页面的cookies取出来,然后再给index.php页面生成cookies是吗?请详解,谢谢!
参考代码:
  String poststr = null;
  string cookie;
  poststr += "username=admin";
  poststr += "&userpw=a1b2c3d4";
  //poststr += "&checkbox1=" + ck;
 
  Encoding UTF8 = Encoding.UTF8;
  Byte[] bytePost = UTF8.GetBytes(poststr);
  Stream datas, datar;
  HttpWebRequest objrequest = (HttpWebRequest)HttpWebRequest.Create(url);
  objrequest.Timeout = 100000;
  objrequest.Credentials = CredentialCache.DefaultCredentials;
  objrequest.Method = "Post";
  objrequest.ContentLength = bytePost.LongLength;
  //objrequest.ContentType = "application/x-www-url-encoded";
  objrequest.ContentType = "application/x-www-form-urlencoded";
  datas = objrequest.GetRequestStream();
  datas.Write(bytePost, 0, bytePost.Length);
  datas.Close();
 
  WebResponse objresponse = objrequest.GetResponse();
  datar = objresponse.GetResponseStream();
  StreamReader r = new StreamReader(datar);
  strRec = r.ReadToEnd();
  cookie = objresponse.Headers.Get("Set-Cookie");
  CookieContainer co = new CookieContainer();
  co.SetCookies(new Uri("http://127.0.0.1/check.php"), cookie);
  objrequest.CookieContainer = co;
  datar.Close();
  r.Close();
  objresponse.Close();

------解决方案--------------------
ding
------解决方案--------------------
冒泡帮顶接分

objrequest.CookieContainer
------解决方案--------------------
CookieContainer
------解决方案--------------------
参考
http://www.cnblogs.com/mysword007/archive/2008/11/09/1330025.html
http://www.cnblogs.com/thunderdanky/articles/819147.html