在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對象發送新的請求。最后可以處理重定向后的響應。