您好,登錄后才能下訂單哦!
在C#中,處理HTTP請求重定向通常是使用HttpClient
類
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace HttpRedirectExample
{
class Program
{
static async Task Main(string[] args)
{
var url = "https://example.com/some-redirect-url";
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.AllowAutoRedirect = false; // 禁用自動重定向
using (var httpClient = new HttpClient(httpClientHandler))
{
try
{
var response = await httpClient.GetAsync(url);
if (response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.MovedPermanently)
{
var redirectUrl = response.Headers.Location.ToString();
Console.WriteLine($"Redirect detected, new URL: {redirectUrl}");
// 手動處理重定向
var redirectResponse = await httpClient.GetAsync(redirectUrl);
if (redirectResponse.IsSuccessStatusCode)
{
var content = await redirectResponse.Content.ReadAsStringAsync();
Console.WriteLine($"Content from redirected URL: {content}");
}
else
{
Console.WriteLine($"Error: {redirectResponse.StatusCode}");
}
}
else if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Content: {content}");
}
else
{
Console.WriteLine($"Error: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}
}
}
在這個示例中,我們首先創建一個HttpClientHandler
實例,將其AllowAutoRedirect
屬性設置為false
以禁用自動重定向。然后,我們使用HttpClient
發送GET請求到指定的URL。如果響應狀態碼表示重定向(例如,HttpStatusCode.Redirect
或HttpStatusCode.MovedPermanently
),我們從響應頭中獲取新的URL,并手動發送另一個GET請求。最后,我們處理重定向后的響應并輸出結果。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。