WebRequest Post 及Get 数据
1 public class WebRequestHelper 2 { 3 /// <summary> 4 /// 以POST 形式请求数据 5 /// </summary> 6 /// <param name="RequestPara"></param> 7 /// <param name="Url"></param> 8 /// <returns></returns> 9 public static string PostData(string RequestPara,string Url) 10 { 11 WebRequest hr = HttpWebRequest.Create(Url); 12 13 byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara); 14 hr.ContentType = "application/x-www-form-urlencoded"; 15 hr.ContentLength = buf.Length; 16 hr.Method = "POST"; 17 18 System.IO.Stream RequestStream = hr.GetRequestStream(); 19 RequestStream.Write(buf, 0, buf.Length); 20 RequestStream.Close(); 21 22 System.Net.WebResponse response = hr.GetResponse(); 23 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")); 24 string ReturnVal = reader.ReadToEnd(); 25 reader.Close(); 26 response.Close(); 27 28 return ReturnVal; 29 } 30 31 /// <summary> 32 /// 以GET 形式获取数据 33 /// </summary> 34 /// <param name="RequestPara"></param> 35 /// <param name="Url"></param> 36 /// <returns></returns> 37 38 public static string GetData(string RequestPara, string Url) 39 { 40 RequestPara=RequestPara.IndexOf('?')>-1?(RequestPara):("?"+RequestPara); 41 42 WebRequest hr = HttpWebRequest.Create(Url + RequestPara); 43 44 byte[] buf = System.Text.Encoding.GetEncoding("utf-8").GetBytes(RequestPara); 45 hr.Method = "GET"; 46 47 System.Net.WebResponse response = hr.GetResponse(); 48 StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")); 49 string ReturnVal = reader.ReadToEnd(); 50 reader.Close(); 51 response.Close(); 52 53 return ReturnVal; 54 } 55 }