request.AllowAutoRedirect=true时,是否还能获得301/302状态码?
发布网友
发布时间:2022-05-18 13:32
我来回答
共1个回答
热心网友
时间:2023-10-17 08:35
这个很简单的,你稍等,我写个示例 给你
private string GetWebString(string url)
{
HttpWebRequest h = (HttpWebRequest)HttpWebRequest.Create(url);
h.AllowAutoRedirect = false;
HttpWebResponse r = (HttpWebResponse)h.GetResponse();
//判断是否重定向 Ambiguous 300 Found 302 Moved 301
if (r.StatusCode == HttpStatusCode.Ambiguous || r.StatusCode == HttpStatusCode.Found || r.StatusCode == HttpStatusCode.Moved)
{
string newUrl = r.Headers["Location"];//获取重定向的网址
if (!string.IsNullOrEmpty(newUrl))
{
//此处做你的处理
r.Close();
//获取源码
return GetWebString(newUrl);
}
}
else
{
using (System.IO.StreamReader read = new System.IO.StreamReader(r.GetResponseStream()))
{
string value = read.ReadToEnd();
r.Close();
return value;
}
}
}