首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在C#中使用WebClient有没有办法在重定向后获取站点的URL?

在C#中,使用WebClient可以通过设置AllowAutoRedirect属性为false来阻止自动重定向,并通过检查响应头中的Location属性来获取重定向后的URL。

以下是一个示例代码:

代码语言:csharp
复制
using System;
using System.Net;

class Program
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
        client.AllowAutoRedirect = false;

        try
        {
            WebResponse response = client.OpenRead("https://example.com");
            string location = response.Headers["Location"];
            Console.WriteLine("Redirected URL: " + location);
        }
        catch (WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                HttpWebResponse response = (HttpWebResponse)ex.Response;
                if (response.StatusCode == HttpStatusCode.Redirect || response.StatusCode == HttpStatusCode.MovedPermanently)
                {
                    string location = response.Headers["Location"];
                    Console.WriteLine("Redirected URL: " + location);
                }
                else
                {
                    Console.WriteLine("Error: " + response.StatusCode);
                }
            }
            else
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

在上面的示例代码中,我们创建了一个WebClient对象,并将AllowAutoRedirect属性设置为false,以阻止自动重定向。然后,我们尝试使用OpenRead方法打开一个URL,如果响应状态码为重定向或永久移动,则从响应头中获取Location属性的值,即为重定向后的URL。如果出现其他错误,则输出错误信息。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

8分3秒

Windows NTFS 16T分区上限如何破,无损调整块大小到8192的需求如何实现?

16分8秒

人工智能新途-用路由器集群模仿神经元集群

领券