HttpService帮助类,POST方法和Get方法
1 public class HttpServiceHelper 2 { 3 public static string Post(string xml, string url, int timeout) 4 { 5 System.GC.Collect();//垃圾回收,回收没有正常关闭的http连接 6 string result = "";//返回结果 7 HttpWebRequest request = null; 8 HttpWebResponse response = null; 9 Stream reqStream = null; 10 11 try 12 { 13 //设置最大连接数 14 ServicePointManager.DefaultConnectionLimit = 200; 15 request = (HttpWebRequest)WebRequest.Create(url); 16 17 request.Method = "POST"; 18 request.Timeout = timeout * 1000; 19 20 //设置POST的数据类型和长度 21 request.ContentType = "application/json"; 22 byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); 23 request.ContentLength = data.Length; 24 //往服务器写入数据 25 reqStream = request.GetRequestStream(); 26 reqStream.Write(data, 0, data.Length); 27 reqStream.Close(); 28 29 //获取服务端返回 30 response = (HttpWebResponse)request.GetResponse(); 31 32 //获取服务端返回数据 33 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 34 result = sr.ReadToEnd().Trim(); 35 sr.Close(); 36 } 37 catch (Exception ex) 38 { 39 return ex.Message.ToString(); 40 } 41 finally 42 { 43 //关闭连接和流 44 if (response != null) 45 { 46 response.Close(); 47 } 48 if (request != null) 49 { 50 request.Abort(); 51 } 52 } 53 return result; 54 } 55 56 /// <summary> 57 /// 处理http GET请求,返回数据 58 /// </summary> 59 /// <param name="url">请求的url地址</param> 60 /// <returns>http GET成功后返回的数据,失败抛WebException异常</returns> 61 public static string Get(string url) 62 { 63 System.GC.Collect(); 64 string result = ""; 65 66 HttpWebRequest request = null; 67 HttpWebResponse response = null; 68 69 //请求url以获取数据 70 try 71 { 72 //设置最大连接数 73 ServicePointManager.DefaultConnectionLimit = 200; 74 75 request = (HttpWebRequest)WebRequest.Create(url); 76 77 request.Method = "GET"; 78 //获取服务器返回 79 response = (HttpWebResponse)request.GetResponse(); 80 81 //获取HTTP返回数据 82 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 83 result = sr.ReadToEnd().Trim(); 84 sr.Close(); 85 } 86 catch (Exception ex) 87 { 88 return ex.Message.ToString(); 89 } 90 finally 91 { 92 //关闭连接和流 93 if (response != null) 94 { 95 response.Close(); 96 } 97 if (request != null) 98 { 99 request.Abort(); 100 } 101 } 102 return result; 103 } 104 }