在C#中,可以通过HttpWebResponse类和HttpWebRequest类来实现重定向。以下是使用301和302状态码进行重定向的示例代码:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.MovedPermanently)
{
string newUrl = response.Headers["Location"];
request = (HttpWebRequest)WebRequest.Create(newUrl);
response = (HttpWebResponse)request.GetResponse();
// 处理重定向后的响应
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
request.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.Found)
{
string newUrl = response.Headers["Location"];
request = (HttpWebRequest)WebRequest.Create(newUrl);
response = (HttpWebResponse)request.GetResponse();
// 处理重定向后的响应
}
在上面的示例中,首先创建一个HttpWebRequest对象,并设置AllowAutoRedirect属性为false,这样可以禁止自动处理重定向。然后发送HTTP请求并检查响应的状态码,如果是301或302状态码,则获取重定向的新URL,并创建一个新的HttpWebRequest对象发送新的请求。最后可以处理重定向后的响应。