如何在C#中使用HttpClient获取所有重定向的URL列表

时间:2015-08-27 15:50:52

标签: c# dotnet-httpclient

Java中是否有类似的内容:HTTPClient - Capture a list of all Redirects

用于C#HttpClient?

1 个答案:

答案 0 :(得分:3)

您可以使用HttpWebRequest执行此操作:

public static string GetRedirectedUrls(string url)
{
    StringBuilder sb = new StringBuilder();
    while (!string.IsNullOrWhiteSpace(url))
    {
        sb.AppendLine(url);
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);
        request.AllowAutoRedirect = false;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            url = response.GetResponseHeader("Location");
        }
    }

    return sb.ToString();
}