WebClient的"尝试自动重定向的次数太多"错误
WebClient myWebClient1 = new WebClient();
textBox1.Text = myWebClient1.DownloadString(url);
一般的网页WebClient都能正常的下载,但某些个别网站下载时会出现“尝试自动重定向的次数太多”的错误,用HttpWebRequest问题依旧,请问下如何解决?谢谢了!
另:下载出错的网页是在内网,所以无法地址贴出来。
[解决办法]
1,可以设置HttpWebRequest 的MaximumAutomaticRedirections 属性一个比较大的值试试
2,如果你的页面也要验证进行访问,如果不保存登录信息,则会不停地进行验证、返回进行循环。如果需要登录验证,使用 CookieContainer 保存登录信息,此方面的文章网上都能搜索到
[解决办法]
正如我上次回复的... 你需要手动分析HTML, 获取转向地址, 进行处理.
- C# code
private string GetHTML(string url, string cookie) { if (String.IsNullOrEmpty(url)) { return null; } else { try { url = url.Replace(" ", "%20"); url = url.Replace("&", "&"); } catch { } } string html = null; string curCookie = null; HttpWebRequest myRequest = null; HttpWebResponse myResp = null; StreamReader myReader = null; for (int i = 0; i < 3; i++) { try { myRequest = (HttpWebRequest)WebRequest.Create(url); myRequest.AllowAutoRedirect = false; myRequest.Timeout = 60 * 1000; myRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"; myRequest.Headers.Add("Cookie", cookie); myRequest.KeepAlive = true; myResp = (HttpWebResponse)myRequest.GetResponse(); curCookie = myResp.Headers["Set-Cookie"]; curCookie = curCookie.Substring(0, curCookie.IndexOf(";")); myReader = new StreamReader(myResp.GetResponseStream(), Encoding.Default, true); html = myReader.ReadToEnd(); } catch (Exception e) { // Console.WriteLine(e.ToString()); continue; } finally { if (myReader != null) { myReader.Close(); } if (myResp != null) { myResp.Close(); } } if (html == null) { continue; } else if (html.IndexOf("Object moved") > 0) //手动获取转向地址,再次获取html代码 { int pos1 = html.IndexOf("http://"); int pos2 = html.IndexOf("\">"); url = html.Substring(pos1, pos2 - pos1); html = GetHTML(url, curCookie); } break; } return html; }