c# - 一种计算重定向 URL 的方法

标签 c# url redirect

给定一个重定向到第三方网站 B 的 URL A,在我的应用程序中,我需要找出给定 url A 的 URL B 并将其插入 DB ,这可以是 Windows 应用程序或 Web 或任何一种方式使用 C# 更快更容易! 谢谢!

附言我不需要将代码插入数据库。

最佳答案

WebRequest 遵循重定向而无需用户干预,因此如果重定向使用 301/302 状态代码,则以下将起作用

WebRequest request = WebRequest.Create(destination);
WebResponse response = request.GetResponse();
Console.WriteLine(response.ResponseUri);

如果重定向是使用 javascript 或 HTTP-Equiv 元标记创建的,那么您必须解析页面并查找它们。 HTML 敏捷包可能是执行此操作的最佳方式。

为了更进一步,下面是一个类,它将手动解析主要的 HTTP 重定向状态代码,并在运行过程中建立历史记录

/// <summary>
/// Digs through HTTP redirects until a non-redirected URL is found.
/// </summary>
public class Digger
{
    /// <summary>
    /// Initializes a new instance of the <see cref="Digger"/> class.
    /// </summary>
    public Digger() : this(20)
    {            
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Digger"/> class.
    /// </summary>
    /// <param name="maximumDepth">The maximum depth of redirects to parse.</param>
    public Digger(int maximumDepth)
    {
        this.MaximumDepth = maximumDepth;
    }

    /// <summary>
    /// Gets the maximum depth of redirects to parse.
    /// </summary>
    /// <value>The maximum depth of redirects to parse.</value>
    public int MaximumDepth
    {
        get; 
        private set;
    }

    /// <summary>
    /// Resolves any redirects at the specified URI.
    /// </summary>
    /// <param name="destination">The initial URI.</param>
    /// <returns>The URI after resolving any HTTP redirects.</returns>
    public Uri Resolve(Uri destination)
    {
        List<Uri> redirectHistory = new List<Uri>();
        return this.Resolve(destination, redirectHistory);
    }

    /// <summary>
    /// Resolves any redirects at the specified URI.
    /// </summary>
    /// <param name="destination">The initial URI.</param>
    /// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param>
    /// <returns>The URI after resolving any HTTP redirects.</returns>
    public Uri Resolve(Uri destination, ICollection<Uri> redirectHistory)
    {
        redirectHistory.Add(destination);
        return this.Resolve(destination, this.MaximumDepth, redirectHistory);
    }

    /// <summary>
    /// Resolves any redirects at the specified URI.
    /// </summary>
    /// <param name="destination">The initial URI.</param>
    /// <param name="hopsLeft">The maximum number of redirects left to follow.</param>
    /// <param name="redirectHistory">A collection of <see cref="Uri"/> objects representing the redirect history.</param>
    /// <returns>The URI after resolving any HTTP redirects.</returns>
    private Uri Resolve(Uri destination, int hopsLeft, ICollection<Uri> redirectHistory)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destination);
        request.AllowAutoRedirect = false;
        request.Method = "HEAD";

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        Uri resolvedUri;

        if (response.StatusCode == HttpStatusCode.Redirect || 
            response.StatusCode == HttpStatusCode.Moved || 
            response.StatusCode == HttpStatusCode.MovedPermanently)
        {
            if (hopsLeft > 0)
            {
                Uri redirectUri = new Uri(response.GetResponseHeader("Location"));
                if (redirectHistory.Contains(redirectUri))
                {
                    throw new Exception("Recursive redirection found");
                }

                redirectHistory.Add(redirectUri);
                resolvedUri = this.Resolve(redirectUri, hopsLeft - 1, redirectHistory);
            }
            else
            {
                throw new Exception("Maximum redirect depth reached");
            }
        }
        else
        {
            resolvedUri = response.ResponseUri;
        }

        return resolvedUri;            
    }
}

关于c# - 一种计算重定向 URL 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1382646/

相关文章:

c# - .Net Core找不到原生dll,.Net Framework可以找到

c# - 在整个程序中 typedef 原始类型的简单方法?

c# - 错误 : "an object reference is required for the non-static field, method or property..."

android从编辑文本中获取url并在rest api中使用它来上传数据

python - 为什么子进程标准输出到文件的顺序是乱写的?

php - 如何使用 slim 的重定向

c# - 如何在 C# 中使用教科书 RSA 加密 ASCII 字符?

ios - 如何从 iOS 应用程序中的 Safari url 获取响应数据?

java - 如何自定义响应错误 400 错误请求

php - htaccess 搜索查询重定向/重写