C#的HttpWebRequest编程,支持带ViewState的网页POST请求
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 staticprivatestring SearchURL(string id) 2 { 3 try 4 { 5 //Get the ViewState and EventValidation 6 HttpWebRequest request = WebRequest.Create(URI) as HttpWebRequest; 7 request.Method ="GET"; 8 request.KeepAlive =false; 9 10 //Get the response 11 HttpWebResponse response = request.GetResponse() as HttpWebResponse; 12 System.IO.Stream responseStream = response.GetResponseStream(); 13 System.IO.StreamReader reader =new System.IO.StreamReader(responseStream, Encoding.UTF8); 14 string srcString = reader.ReadToEnd(); 15 16 //Get the ViewState 17 string viewStateFlag ="id=\"__VIEWSTATE\" value=\""; 18 int i = srcString.IndexOf(viewStateFlag) + viewStateFlag.Length; 19 int j = srcString.IndexOf("\"", i); 20 string viewState = srcString.Substring(i, j - i); 21 22 //Get the ViewState 23 string EventValidationFlag ="id=\"__EVENTVALIDATION\" value=\""; 24 i = srcString.IndexOf(EventValidationFlag) + EventValidationFlag.Length; 25 j = srcString.IndexOf("\"", i); 26 string eventValidation = srcString.Substring(i, j - i); 27 28 //Compose the URL 29 viewState = Uri.EscapeDataString(viewState); 30 eventValidation = Uri.EscapeDataString(eventValidation); 31 string strSearch = Uri.EscapeDataString("查询"); 32 33 string formatString ="__VIEWSTATE={0}&__EVENTVALIDATION={1}&TextBox1={2}&Button1={3}"; 34 string postString =string.Format(formatString, viewState, eventValidation, id,strSearch); 35 36 //Change to byte[] 37 byte[] postData = Encoding.ASCII.GetBytes(postString); 38 39 //Compose the new request 40 request = WebRequest.Create(URI) as HttpWebRequest; 41 request.Method ="POST"; 42 request.KeepAlive =false; 43 request.ContentType ="application/x-www-form-urlencoded"; 44 request.ContentLength = postData.Length; 45 46 System.IO.Stream outputStream = request.GetRequestStream(); 47 outputStream.Write(postData, 0, postData.Length); 48 outputStream.Close(); 49 50 //Get the new response 51 response = request.GetResponse() as HttpWebResponse; 52 responseStream = response.GetResponseStream(); 53 reader =new System.IO.StreamReader(responseStream); 54 srcString = reader.ReadToEnd(); 55 return srcString; 56 } 57 catch (WebException we) 58 { 59 Console.WriteLine("Communication error,"+ we.Message +" please check your connectivity and try again.", "Error"); 60 } 61 catch 62 { 63 Console.WriteLine("Unknow error.", "Error"); 64 } 65 returnnull; 66 }
工欲善其事,必先利其器。