c#

C# HttpRequestMessage如何追踪重定向

小樊
85
2024-08-05 13:29:12
栏目: 编程语言

要追踪重定向,可以使用HttpClientHandler类来处理重定向。以下是一个示例代码:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        using (HttpClientHandler handler = new HttpClientHandler())
        {
            handler.AllowAutoRedirect = false; // 禁止自动重定向

            using (HttpClient client = new HttpClient(handler))
            {
                HttpResponseMessage response = await client.GetAsync("https://example.com");

                if (response.StatusCode == System.Net.HttpStatusCode.Found || // 302
                    response.StatusCode == System.Net.HttpStatusCode.MovedPermanently) // 301
                {
                    string redirectUrl = response.Headers.Location.AbsoluteUri;
                    Console.WriteLine("Redirected to: " + redirectUrl);
                }
            }
        }
    }
}

在此示例中,我们使用HttpClientHandler类创建了一个带有禁止自动重定向功能的HttpClient实例。当发送GET请求时,如果返回的状态码是302(Found)或301(Moved Permanently),则可以从响应头中获取重定向的URL。

0
看了该问题的人还看了