默认的getUrlRespHtml只允许一次,即当出错时,就返回空字符串了,就不再继续了。
此处的getUrlRespHtml_multiTry,是带多次尝试的版本。
其完整代码是:
public string getUrlRespHtml_multiTry (string url, Dictionary<string, string> headerDict = defHeaderDict, string charset = defCharset, Dictionary<string, string> postDict = defPostDict, int timeout = defTimeout, string postDataStr = defPostDataStr, int readWriteTimeout = defReadWriteTimeout, int maxTryNum = defMaxTryNum, int retryFailSleepTime = defRetryFailSleepTime) { string respHtml = ""; for (int tryIdx = 0; tryIdx < maxTryNum; tryIdx++) { respHtml = getUrlRespHtml(url, headerDict, charset, postDict, timeout, postDataStr, readWriteTimeout); if (!string.IsNullOrEmpty(respHtml)) { break; } else { //something wrong //maybe network is not stable //so wait some time, then re-do it System.Threading.Thread.Sleep(retryFailSleepTime); } } return respHtml; }
很明显可以看出,此处的getUrlRespHtml_multiTry的很多参数,和前面介绍的第 9.6 节 “获得Url地址返回的网页内容:getUrlRespHtml”非常类似。
此处,还有另外两个参数,需要解释一下:
maxTryNum表示最大(当出错时)重试次数。
maxTryNum默认值是defMaxTryNum
defMaxTryNum的值是5:
private const int defMaxTryNum = 5;
当你需要,在出错时,重试更多次,则可以修改此参数。
retryFailSleepTime表示在每次出错之后,sleep的时间。
retryFailSleepTime默认值是defRetryFailSleepTime
defRetryFailSleepTime的值是100毫秒:
private const int defRetryFailSleepTime = 100; //sleep time in ms when retry fail for getUrlRespHtml
此处,是为了,尽量适应网络不稳定等异常情况,在出错后,sleep一段时间重试,以希望实现,网络不稳定的时候,经过多次尝试,且每次错误后会sleep,达到增大网络访问成功的机会。
例 9.8. getUrlRespHtml_multiTry 的使用范例
//respHtml = crl.getUrlRespHtml(viewHtmlUrl); respHtml = crl.getUrlRespHtml_multiTry(viewHtmlUrl);