HttpWebRequest访问页面为何总是超时?

crystal_lz 2015-04-08 06:31:17
同样的代码前几天还是好好的 可是不知道为什么 突然之间就开始timeout了
然后百度看到了很多说法 感觉都不靠谱
有说要把Methon设置成Get
有说要把Timeout设置大一点(我网络没有问题 浏览器秒开 ping百度几十延迟 程序5秒的timeout却超时)
还有说把用完要记得close 然后重置对象为null(我是close 但是为什么要重置为null就感觉是在扯淡)
还有说把限制连接数设置大一点
- -!、、反正感觉没有一个靠谱的 后来我直接抓包发现 根本就没有数据包发送出去就timeout了

5秒的超时 根本就没有包出去 要是有包出去timeout我还能理解 包都没有出去就不知道为什么了(ping的包被我清空了的 不是电脑问题- -!)
下面是我访问的代码:

public static RequestResult GetUrlHtml(string strUrl, string strRef, int nTimeOut, CookieContainer ckContainer) {
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebRespones = null;
string strHtml = string.Empty;
if (!Regex.IsMatch(strUrl, @"^https?://", RegexOptions.IgnoreCase)) strUrl = "http://" + strUrl;
httpWebRequest = WebRequest.Create(strUrl) as HttpWebRequest;
httpWebRequest.Method = "GET";
httpWebRequest.Timeout = nTimeOut;
httpWebRequest.ReadWriteTimeout = 60000;
httpWebRequest.AllowAutoRedirect = true;
httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; Maxthon 2.0)";
if (!string.IsNullOrEmpty(strRef)) httpWebRequest.Referer = strRef;
if (ckContainer != null) httpWebRequest.CookieContainer = ckContainer;
httpWebRespones = (HttpWebResponse)httpWebRequest.GetResponse();//timeout....
if (httpWebRespones.ContentType.ToLower().IndexOf("text/html") == -1) return new RequestResult(httpWebRequest, httpWebRespones, null);
using (Stream stream = httpWebRespones.GetResponseStream()) {
string strCharSet = Regex.Match(httpWebRespones.ContentType, @"charset=(\w+)", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
List<byte> lst = new List<byte>();
int nRead = 0;
while ((nRead = stream.ReadByte()) != -1) lst.Add((byte)nRead);
byte[] byHtml = lst.ToArray();
if (strCharSet == "") {
strHtml = Encoding.UTF8.GetString(byHtml, 0, byHtml.Length);
strCharSet = Regex.Match(strHtml, @"<meta.*?charset=""?([a-z0-9-]+)\b", RegexOptions.IgnoreCase).Groups[1].Value;
if (strCharSet.ToLower().IndexOf("utf") == -1) {
try {
strHtml = Encoding.GetEncoding(strCharSet).GetString(byHtml, 0, byHtml.Length);
} catch { }
}
} else {
try {
strHtml = Encoding.GetEncoding(strCharSet).GetString(byHtml, 0, byHtml.Length);
} catch {
strHtml = Encoding.UTF8.GetString(byHtml, 0, byHtml.Length);
}
}
}
httpWebRespones.Close();
return new RequestResult(httpWebRequest, httpWebRespones, strHtml);
}

已经搞了一天了。不知道为什么 虽然想用socket直接去连接 但是想着要自己解析包 也是麻烦事情
...全文
233 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
crystal_lz 2015-04-08
  • 打赏
  • 举报
回复
再次强调 网络没有问题 所以如果说 告诉我 判断出现异常就再访问一次什么的就算了 就像楼上说的 有大于二分之一的情况都会出现timeout异常 都去尝试还得了 而且本来网络就没有问题 我想知道是什么情况导致的包都没有发出去 为什么5秒钟都没有发包 这5秒钟它都干嘛去了。。。
crystal_lz 2015-04-08
  • 打赏
  • 举报
回复
并不是每次都timeout 有大于二分之一的情况都是timeout 不知道为什么会这样

111,120

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧