代码改变世界

WebClient 尝试自动重定向的次数太多

2014-12-09 10:24  minco  阅读(2289)  评论(0)    收藏  举报

最近在使用WebClient 获取页面的时候,报了一个“尝试自动重定向的次数太多” 的错误。

Google 一下便轻松找到解决办法,使用HttpWebRequest 来解决,代码如下:

 HttpWebRequest myRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(你要获取的页面URL);  
 
 CookieContainer cc = new CookieContainer();
 
 myRequest.CookieContainer = cc;
  //后面代码省略   

加了这段代码之后错误是没有了,但是发现获取到的页面不是我想要的。

因为我Post 的页面需要Cookie,所以刚开始,我直接在

myRequest.Headers.Set("Cookie", cookie);里面加入我第一次Post时获取到的Cookie。 但拿到的页面根本不是我想要的。
注意:由于需要传入Cookie值, 所以我这里写了一个循环。 第一次POST 获取需要的Cookie,传入下一次的Post请求(第二次Post的时候不需要CookieContainer ,否则拿不到想要的页面)。

 

string hHtmlResult = string.Empty, cookie = string.Empty;
do
{
    HttpWebRequest myRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(URI);
    myRequest.Method = "POST";
    myRequest.ContentType = "application/x-www-form-urlencoded";
    myRequest.AllowAutoRedirect = true;
    myRequest.Timeout = 60 * 1000;
    myRequest.MaximumAutomaticRedirections = 50;
    myRequest.Referer = URI;
    myRequest.KeepAlive = true;
    myRequest.Headers.Set("Cookie", cookie);
    myRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36";
    CookieContainer cc = new CookieContainer();                   
    //myRequest.CookieContainer = cc; 直接这样写有问题,获取不到想要的页面,需要加个下面的判断
    if (string.IsNullOrEmpty(cookie))
    {
       myRequest.CookieContainer = cc;
    }
  
    Stream newStream = myRequest.GetRequestStream();
    newStream.Write(postData, 0, postData.Length);
    newStream.Close();

    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

    using (Stream s = myResponse.GetResponseStream())
    {
        StreamReader objReader = new StreamReader(s, System.Text.Encoding.UTF8);
        HtmlResult = objReader.ReadToEnd();
        //如果有拿到想要的页面,就直接通过正则或其他方式提取数据(HtmlAgilityPack)
        if (HtmlResult.Contains(tracking))
        {
            // code
        }
        else
        {
            cookie = myRequest.Headers.Get("Cookie");
        }
    }

} while (!HtmlResult.Contains(tracking));   //我这里如果没有返回我需要的页面,就继续循环。