原创标准HTTP请求工具类
Posted lichunting
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原创标准HTTP请求工具类相关的知识,希望对你有一定的参考价值。
以下是个人在项目开发过程中,总结的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请求工具类的主要内容,如果未能解决你的问题,请参考以下文章
elasticsearch代码片段,及工具类SearchEsUtil.java
《安富莱嵌入式周报》第279期:强劲的代码片段搜索工具,卡内基梅隆大学安全可靠C编码标准,Nordic发布双频WiFi6 nRF7002芯片