【原理】
【代码】
1 private void button2_Click(object sender, EventArgs e) 2 { 3 string url =“请求的地址” 4 indata = “传入的数据&传入的数据”; 5 string outdata = ""; 6 byte[] data = System.Text.Encoding.UTF8.GetBytes(indata); 7 8 //新建一个HttpWebRequest 9 HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 10 11 //一定要设置ContentType 12 myHttpWebRequest.ContentType = "application/x-www-form-urlencoded"; 13 myHttpWebRequest.ContentLength = data.Length; 14 myHttpWebRequest.Method = "POST"; 15 16 //新建一个CookieContainer来存放Cookie集合 17 CookieContainer myCookieContainer = new CookieContainer(); 18 19 //设置HttpWebRequest的CookieContainer为刚才建立的那个myCookieContainer 20 myHttpWebRequest.CookieContainer = myCookieContainer; 21 22 //把数据写入HttpWebRequest的Request流 23 Stream myRequestStream = myHttpWebRequest.GetRequestStream(); 24 myRequestStream.Write(data, 0, data.Length); 25 StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("utf-8")); 26 27 //关闭打开对象 28 myRequestStream.Flush(); 29 myRequestStream.Close(); 30 31 //新建一个HttpWebResponse 32 HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 33 34 //把数据从HttpWebResponse的Response流中读出 35 Stream myResponseStream = myHttpWebResponse.GetResponseStream(); 36 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 37 outdata = myStreamReader.ReadToEnd(); 38 39 //关闭打开的对象 40 myStreamReader.Close(); 41 myResponseStream.Close(); 42 43 //显示"登录" 44 //拿到了Cookie,再进行请求就能直接读取到登录后的内容了 45 myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 46 47 //刚才那个CookieContainer已经存有了Cookie,把它附加到HttpWebRequest中则能直接通过验证 48 myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 49 50 //读取登陆后的内容 51 myResponseStream = myHttpWebResponse.GetResponseStream(); 52 myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); 53 outdata = myStreamReader.ReadToEnd(); 54 55 //关闭打开的对象 56 myStreamReader.Close(); 57 myResponseStream.Close(); 58 59 Console.WriteLine(outdata); 60 this.webBrowser1.DocumentText = outdata; 61 }
【备注】
当Cookie被设置为HttpOnly时,此方法就无法获取Cookie了,关于HttpOnly的限制,下一篇文章将继续研究。