1. 程式人生 > >【原創】標準HTTP請求工具類

【原創】標準HTTP請求工具類

dto case 開發 utf ignore pst new mar name

以下是個人在項目開發過程中,總結的Http請求工具類,主要包括四種:

1.處理http POST請求【XML格式、無解壓】;

2.處理http GET請求【XML格式、無解壓】;

3.處理http POST請求【可以解壓】;

4.處理http GET請求【可以解壓】。

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.IO.Compression;
  5 using System.Linq;
  6 using System.Net;
7 using System.Net.Security; 8 using System.Security.Cryptography.X509Certificates; 9 using System.Text; 10 using System.Threading.Tasks; 11 12 namespace Common 13 { 14 public class HttpService 15 { 16 public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
17 { 18 //直接確認,否則打不開 19 return true; 20 } 21 22 #region 1.處理http POST請求【XML格式、無解壓】 23 /// <summary> 24 /// 處理http POST請求【XML格式、無解壓】 25 /// </summary> 26 /// <param name="xml">請求參數</param> 27 ///
<param name="url">請求接口地址</param> 28 /// <param name="timeout">設置超時時間</param> 29 /// <returns>http POST成功後返回的數據,失敗拋WebException異常</returns> 30 public static string PostXMLRequest(string xml, string url, int timeout = 16) 31 { 32 System.GC.Collect();//垃圾回收,回收沒有正常關閉的http連接 33 34 string result = "";//返回結果 35 36 HttpWebRequest request = null; 37 HttpWebResponse response = null; 38 Stream reqStream = null; 39 40 try 41 { 42 //設置最大連接數 43 ServicePointManager.DefaultConnectionLimit = 200; 44 //設置https驗證方式 45 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 46 { 47 ServicePointManager.ServerCertificateValidationCallback = 48 new RemoteCertificateValidationCallback(CheckValidationResult); 49 } 50 51 /*************************************************************** 52 * 下面設置HttpWebRequest的相關屬性 53 * ************************************************************/ 54 request = (HttpWebRequest)WebRequest.Create(url); 55 56 request.Method = "POST"; 57 request.Timeout = timeout * 1000; 58 59 //設置POST的數據類型和長度 60 request.ContentType = "text/xml"; 61 byte[] data = System.Text.Encoding.UTF8.GetBytes(xml); 62 request.ContentLength = data.Length; 63 64 //往服務器寫入數據 65 reqStream = request.GetRequestStream(); 66 reqStream.Write(data, 0, data.Length); 67 reqStream.Close(); 68 69 //獲取服務端返回 70 response = (HttpWebResponse)request.GetResponse(); 71 72 //獲取服務端返回數據 73 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 74 result = sr.ReadToEnd().Trim(); 75 sr.Close(); 76 } 77 catch (System.Threading.ThreadAbortException e) 78 { 79 System.Threading.Thread.ResetAbort(); 80 } 81 catch (WebException e) 82 { 83 84 85 } 86 catch (Exception e) 87 { 88 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 #endregion 105 106 #region 2.處理http GET請求【XML格式、無解壓】 107 /// <summary> 108 /// 處理http GET請求【XML格式、無解壓】 109 /// </summary> 110 /// <param name="url">請求的url地址</param> 111 /// <returns>http GET成功後返回的數據,失敗拋WebException異常</returns> 112 public static string GetXMLRequest(string url) 113 { 114 System.GC.Collect(); 115 string result = ""; 116 117 HttpWebRequest request = null; 118 HttpWebResponse response = null; 119 120 //請求url以獲取數據 121 try 122 { 123 //設置最大連接數 124 ServicePointManager.DefaultConnectionLimit = 200; 125 //設置https驗證方式 126 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 127 { 128 ServicePointManager.ServerCertificateValidationCallback = 129 new RemoteCertificateValidationCallback(CheckValidationResult); 130 } 131 132 /*************************************************************** 133 * 下面設置HttpWebRequest的相關屬性 134 * ************************************************************/ 135 request = (HttpWebRequest)WebRequest.Create(url); 136 137 request.Method = "GET"; 138 139 //獲取服務器返回 140 response = (HttpWebResponse)request.GetResponse(); 141 142 //獲取HTTP返回數據 143 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); 144 result = sr.ReadToEnd().Trim(); 145 sr.Close(); 146 } 147 catch (System.Threading.ThreadAbortException e) 148 { 149 150 System.Threading.Thread.ResetAbort(); 151 } 152 catch (WebException e) 153 { 154 155 156 } 157 158 finally 159 { 160 //關閉連接和流 161 if (response != null) 162 { 163 response.Close(); 164 } 165 if (request != null) 166 { 167 request.Abort(); 168 } 169 } 170 return result; 171 } 172 #endregion 173 174 #region 3.處理http POST請求【可以解壓】 175 /// <summary> 176 /// 處理http POST請求【可以解壓】 177 /// </summary> 178 /// <param name="param">請求參數</param> 179 /// <param name="url">請求接口地址</param> 180 /// <param name="timeout">設置超時時間</param> 181 /// <returns>http POST成功後返回的數據,失敗拋WebException異常</returns> 182 public static string Post(string param, string url, int timeout = 16) 183 { 184 System.GC.Collect();//垃圾回收,回收沒有正常關閉的http連接 185 186 string result = "";//返回結果 187 188 HttpWebRequest request = null; 189 HttpWebResponse response = null; 190 Stream reqStream = null; 191 StreamReader sr = null; 192 try 193 { 194 //設置最大連接數 195 ServicePointManager.DefaultConnectionLimit = 200; 196 197 /*************************************************************** 198 * 下面設置HttpWebRequest的相關屬性 199 * ************************************************************/ 200 request = (HttpWebRequest)WebRequest.Create(url); 201 202 request.Method = "POST"; 203 request.Timeout = timeout * 1000; 204 205 //設置POST的數據類型 206 request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; 207 208 byte[] data = System.Text.Encoding.UTF8.GetBytes(param); 209 210 request.UserAgent = "Mozilla/4.0"; 211 request.Headers.Add("Accept-Encoding", "gzip, deflate"); 212 213 //設置POST的數據長度 214 request.ContentLength = data.Length; 215 216 //往服務器寫入數據 217 reqStream = request.GetRequestStream(); 218 reqStream.Write(data, 0, data.Length); 219 reqStream.Close(); 220 221 //獲取服務端返回 222 response = (HttpWebResponse)request.GetResponse(); 223 224 //獲取服務端返回數據 225 if (response.ContentEncoding.ToLower() == "gzip")//如果使用了GZip則先解壓 226 { 227 using (Stream streamReceive = response.GetResponseStream()) 228 { 229 using (var zipStream = new GZipStream(streamReceive, CompressionMode.Decompress)) 230 { 231 using (sr = new StreamReader(zipStream, Encoding.UTF8)) 232 { 233 result = sr.ReadToEnd(); 234 } 235 } 236 } 237 } 238 else 239 { 240 using (Stream streamReceive = response.GetResponseStream()) 241 { 242 using (sr = new StreamReader(streamReceive, Encoding.UTF8)) 243 { 244 result = sr.ReadToEnd(); 245 } 246 } 247 } 248 249 sr.Close(); 250 } 251 catch (System.Threading.ThreadAbortException e) 252 { 253 254 System.Threading.Thread.ResetAbort(); 255 } 256 catch (WebException e) 257 { 258 259 } 260 catch (Exception e) 261 { 262 263 } 264 finally 265 { 266 //關閉連接和流 267 if (response != null) 268 { 269 response.Close(); 270 } 271 if (request != null) 272 { 273 request.Abort(); 274 } 275 } 276 return result; 277 } 278 #endregion 279 280 #region 4.處理http GET請求【可以解壓】 281 /// <summary> 282 /// 處理http GET請求【可以解壓】 283 /// </summary> 284 /// <param name="url">請求的url地址</param> 285 /// <returns>http GET成功後返回的數據,失敗拋WebException異常</returns> 286 public static string Get(string url) 287 { 288 System.GC.Collect(); 289 string result = ""; 290 291 HttpWebRequest request = null; 292 HttpWebResponse response = null; 293 StreamReader sr = null; 294 295 //請求url以獲取數據 296 try 297 { 298 //設置最大連接數 299 ServicePointManager.DefaultConnectionLimit = 200; 300 301 /*************************************************************** 302 * 下面設置HttpWebRequest的相關屬性 303 * ************************************************************/ 304 request = (HttpWebRequest)WebRequest.Create(url); 305 306 request.Method = "GET"; 307 308 //獲取服務器返回 309 response = (HttpWebResponse)request.GetResponse(); 310 311 //獲取HTTP返回數據 312 //獲取服務端返回數據 313 if (response.ContentEncoding.ToLower() == "gzip")//如果使用了GZip則先解壓 314 { 315 using (Stream streamReceive = response.GetResponseStream()) 316 { 317 using (var zipStream = 318 new GZipStream(streamReceive, CompressionMode.Decompress)) 319 { 320 using (sr = new StreamReader(zipStream, Encoding.UTF8)) 321 { 322 result = sr.ReadToEnd(); 323 } 324 } 325 } 326 } 327 else 328 { 329 using (Stream streamReceive = response.GetResponseStream()) 330 { 331 using (sr = new StreamReader(streamReceive, Encoding.UTF8)) 332 { 333 result = sr.ReadToEnd(); 334 } 335 } 336 } 337 sr.Close(); 338 } 339 catch (System.Threading.ThreadAbortException e) 340 { 341 342 System.Threading.Thread.ResetAbort(); 343 } 344 catch (WebException e) 345 { 346 347 if (e.Status == WebExceptionStatus.ProtocolError) 348 { 349 350 } 351 352 } 353 catch (Exception e) 354 { 355 356 } 357 finally 358 { 359 //關閉連接和流 360 if (response != null) 361 { 362 response.Close(); 363 } 364 if (request != null) 365 { 366 request.Abort(); 367 } 368 } 369 return result; 370 } 371 #endregion 372 } 373 }

【原創】標準HTTP請求工具類