c# .net 怎么判断 WebRequest 请求失败了 还是 成功了? 10
2个回答
展开全部
HttpWebRequest请求超时异常的处理方法(重新发送请求到成功为止)
方法主要有2点:1.在GetResponse()超时后要重新发送请求;2.检查是否异常,捕获或抛掉异常。
publicstring GetHtml(string URI) {
string fullhtml=null;
while(true) {
try {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);
req.Method ="GET";
req.UserAgent ="Opera/9.25 (Windows NT 6.0; U; en)";
req.KeepAlive =true; req.Timeout =6000000;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应
continue;
StreamReader sr =new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
fullhtml = sr.ReadToEnd().Trim();
resp.Close();
sr.Close();
break;
}
catch (WebException e) {
e.StackTrace.ToString();
System.Diagnostics.Trace.WriteLine(e.Message);
if (true) continue;
}
}
return fullhtml;
}
方法主要有2点:1.在GetResponse()超时后要重新发送请求;2.检查是否异常,捕获或抛掉异常。
publicstring GetHtml(string URI) {
string fullhtml=null;
while(true) {
try {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URI);
req.Method ="GET";
req.UserAgent ="Opera/9.25 (Windows NT 6.0; U; en)";
req.KeepAlive =true; req.Timeout =6000000;
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
if (resp.StatusCode != HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应
continue;
StreamReader sr =new StreamReader(resp.GetResponseStream(), Encoding.UTF8);
fullhtml = sr.ReadToEnd().Trim();
resp.Close();
sr.Close();
break;
}
catch (WebException e) {
e.StackTrace.ToString();
System.Diagnostics.Trace.WriteLine(e.Message);
if (true) continue;
}
}
return fullhtml;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询