最近在做微信企业号的集成开发,在做对文件的上传和下载时,遇到一个很头疼的问题。程序运行一段时间之后在下载或者上传文件时webclient会报一个基础连接已经关闭:发送时发生错误。
因为程序是运行一段时间后才会报这个错误,所以刚开始以为是资源没有释放,查了代码的基础类,发现资源都是已经释放过的。也怀疑过是不是超出最大连接数,但显而易见不是这个问题。通过在网上查找资料,大家提供了以下几种解决方案:
1、在GetResponse() 前加上这句ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 这句代码是让你的程序适应https请求协议。
2、httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); 在行代码前添加System.GC.Collect(); 用于程序垃圾资源回收
3、如果Http的请求,是设置了KeepAlive=true的话,那么对应的http的connection会和服务器保持连接的。所以如果上述办法都不能解决超时的问题,可以尝试将keepAlive设置为false试试,看看能否解决。
4、httpWebRequest.ServicePoint.ConnectionLimit = maxTry; 默认ConnectionLimit是2个连接数,所以可以通过修改连接数尝试解决该问题。可以改到200-300,但是不要改太大,容易对程序照成压力。
5、另外你初始化的都要在用完之后,进行关闭和回收。(HttpWebRequest HttpWebResponse) 虽然每种开发语言都有自己的回收机制,但是要记着一点再好的人,也有累的时候,累了就不给你干活了,所以平时对它们好点。
如果上面的方法都无法解决你的问题,可以尝试一下我最后的解决方案。
最后我发现只有在一台服务器上面出问题,后来经过查找,发现是这台服务器被配置了代理服务器,通过代理服务器的方式进行外网的访问。所以找到原因就好办了,只要在创建HttpWebRequest 对象之前,在创建一个代理服务器的对象,并且把服务器的代理地址和端口实例化到代理服务器对象。
{
ServicePointManager.Expect100Continue = false;
Thread.Sleep(NetworkDelay);//等待
currentTry++;
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
// byte[] byteRequest = Encoding.Default.GetBytes(postData);
byte[] byteRequest = postData;
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
if (Proxy != null)
httpWebRequest.Proxy = Proxy; //代理服务器设置
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.ContentType = contentType;
httpWebRequest.ServicePoint.ConnectionLimit = maxTry;
httpWebRequest.Referer = refurl;
httpWebRequest.Accept = accept;
httpWebRequest.UserAgent = userAgent;
httpWebRequest.Method = isPost ? "POST" : "GET";
httpWebRequest.ContentLength = byteRequest.Length;
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(byteRequest, 0, byteRequest.Length);
stream.Close();
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, encoding);
string html = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
currentTry = 0;
httpWebRequest.Abort();
httpWebResponse.Close();
foreach (Cookie cookie in httpWebResponse.Cookies)
{
cookieContainer.Add(cookie);
}
return html;
}
catch (Exception)
{
if (httpWebRequest != null)
{
httpWebRequest.Abort();
} if (httpWebResponse != null)
{
httpWebResponse.Close();
}
return "";
}
}