HttpWebRequest使用如下:
第一种:使用Using 释放资源
/// <summary> /// Http Get请求返回数据 /// </summary> /// <param name="url">Http请求URL</param> /// <returns>返回Http请求的结果</returns> public string HttpGetMethod(string url, int timeOut = 10) { string strResult = null; try { if (string.IsNullOrEmpty(url)) { return null; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = timeOut * 1000; using (HttpWebResponse wb = (HttpWebResponse)request.GetResponse()) { using (Stream stream = wb.GetResponseStream()) { using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8)) { strResult = streamReader.ReadToEnd(); } } } } catch (Exception ex) { throw;//LoggerService.Log.Error($"Http Get请求{url}返回数据失败,原因:{ex.ToString()}"); } return strResult; }
第二种:使用close 释放资源
/// <summary> /// Http Get请求返回数据 /// </summary> /// <param name="url">Http请求URL</param> /// <returns>返回Http请求的结果</returns> public string HttpGetMethod2(string url, int timeOut = 10) { if (string.IsNullOrEmpty(url)) { return null; } HttpWebRequest request = null; HttpWebResponse response = null; Stream streamReceive = null; StreamReader streamReader = null; string strResult = null; try { request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = timeOut * 1000; ServicePointManager.DefaultConnectionLimit = 200; response = (HttpWebResponse)request.GetResponse(); streamReceive = response.GetResponseStream(); streamReader = new StreamReader(streamReceive, Encoding.UTF8); strResult = streamReader.ReadToEnd(); streamReader.Close(); streamReader.Dispose(); streamReceive.Close(); streamReceive.Dispose(); response.Close(); request.Abort(); } catch (Exception ex) { throw;// LoggerService.Log.Error($"Http Get请求{url}返回数据失败,原因:{ex.ToString()}"); } finally { if (streamReader != null) { streamReader.Close(); streamReader.Dispose(); } if (streamReceive != null) { streamReceive.Close(); streamReceive.Dispose(); } if (response != null) { response.Close(); } } return strResult; }
HttpWebRequest使用的2种基本写法,各种response,streamReceive ,streamReader 资源都释放了,看似没有什问题,其实只要写个while死循环,每次都去请求,你会发现,运行不了几次就阻塞了,原因很简单就是还有个HttpWebRequest对象没有释放,其实很多时候释放了Stream和Response还远远不够,客户端的Request还是在保持着,无法及时释放占有的资源,而是需要Net的GC.Collect()系统垃圾回收器来回收,因此无法保证资源的及时释放,所以一般很容易阻塞,就会出现上次的请求在处理,导致本次请求发送不出去。HttpWebRequest及时释放就是让HttpWebRequest在不需要的时候及时释放资源,这样可以重复使用而不会阻塞。
在程序的finally中添加下面这句就ok了。
if (request != null)
{
request.Abort();
}