当使用HttpWebRequest进行访问时,结果提示为302重定向错误。
使用代码,
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; request.ContentType = "text/html"; request.AllowAutoRedirect = true;//设置自动重定向 request.ServicePoint.Expect100Continue = true;//设置自动重定向 request.MaximumAutomaticRedirections = 50;//允许最大重定向次数 request.CookieContainer = new CookieContainer(); //request.Timeout = 30000; //request.ReadWriteTimeout = 30000; ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) => { return true; }; request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); var heards = request.GetResponse().Headers; Stream myResponseStream = response.GetResponseStream(); using (StreamReader myStreamReader = new StreamReader(myResponseStream, encoding)) { string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; }
最终发现。是少加了CookieContainer...猜测是由于重定向时候第一个网页往头部添加了一个Cookie这个Cookie发送给重定向地址,所以必须带上CookieContainer。