public string PostData(string url, CookieContainer cookie, string postdata) { HttpWebRequest Request = null; //http请求 HttpWebResponse Response = null;//http响应 string Conntent = string.Empty; Request = (HttpWebRequest)WebRequest.Create(new Uri(url));//创建请求连接 byte[] b = Encoding.UTF8.GetBytes(postdata); // 转化 Request.ContentType = "application/x-www-form-urlencoded"; Request.Method = "POST";//设置请求类型 Request.CookieContainer = cookie;//设置cookie Request.ContentLength = b.Length;//设置推送数据的长度 using (Stream stream = Request.GetRequestStream())//获取用于写入的流 { stream.Write(b, 0, b.Length); } //获取服务器返回的资源 using (Response = (HttpWebResponse)Request.GetResponse())//返回响应资源 { using (StreamReader reader = new StreamReader(Response.GetResponseStream(), Encoding.UTF8))//返回响应流 { if (Response.Cookies.Count > 0)//判断cookie存在 cookie.Add(Response.Cookies);//在cookie集合中添加 Conntent = reader.ReadToEnd();//读取流; } } return Conntent; }
CookieContainer cookie = new CookieContainer();
string LoginPostData = string.Format("gotopage=/oy/&dopost=login&adminstyle=o&userid={0}&pwd={1}", 账号,密码);//登陆post数据
string aa = httphelper.PostData("http://www.qq.com/login.php", cookie, LoginPostData);//登陆
登陆以后 再访问其他的页面,依然跳到登陆页
貌似要用response.Header["Set-Cookie"]去获取,我做webqq登录时取cookies:
private static bool SaveCookies(string qq, QQResponse response) { if (response.Header == null) { return false; } //保存登录成功后的cookie string ckstr = response.Header["Set-Cookie"]; //登录失败 if (ckstr == null) { return false; } CookieContainer cc ; if (QQCookies.Keys.Contains(qq)) { cc = QQCookies[qq]; } else { cc = new CookieContainer(); } string[] items = ckstr.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); string[] kv; string key = ""; foreach (string item in items) { kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries); key = kv[0].Trim(); //去掉不是cookie项目 if (kv.Length < 2 || key == "EXPIRES" || key == "PATH" || key == "DOMAIN") { continue; } cc.Add(new Cookie { Domain = "ptlogin2.qq.com", Name = key, Value = kv[1] }); if (key == "ptwebqq") { PTWebqq[qq] = kv[1]; } } QQCookies[qq] = cc; return true; }
试试我的类http://www.sufeinet.com/thread-3-1-1.html