3

何度かリダイレクトされる可能性のある場所URL Xからのパスを表す URL のリストを取得しようとしています。URL YX

例えば:

http://www.example.com/foo

次の場所にリダイレクトされます。

http://www.example.com/bar

次にリダイレクトします:

http://www.example.com/foobar

このリダイレクト経路を応答オブジェクトから文字列として取得する方法はありますか:http://www.example.com/foo > http://www.example.com/bar > http://www.example.com/foobar

ResponseUriたとえば、最終的なURLにアクセスできます

public static string GetRedirectPath(string url)
{
    StringBuilder sb = new StringBuilder();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    using (var response = (HttpWebResponse)request.GetResponse())
    {
        sb.Append(response.ResponseUri);
    }
    return sb.ToString();
}

しかし、これは明らかにその間の URL をスキップします。完全な経路を取得するための簡単な方法 (またはまったく方法) がないように思われますか?

4

1 に答える 1

9

やり方がある:

public static string RedirectPath(string url)
{
    StringBuilder sb = new StringBuilder();
    string location = string.Copy(url);
    while (!string.IsNullOrWhiteSpace(location))
    {
        sb.AppendLine(location); // you can also use 'Append'
        HttpWebRequest request = HttpWebRequest.CreateHttp(location);
        request.AllowAutoRedirect = false;
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            location = response.GetResponseHeader("Location");
        }
    }
    return sb.ToString();
}

この TinyURL でテストしました: http://tinyurl.com/google
出力:

http://tinyurl.com/google
http://www.google.com/
http://www.google.be/?gws_rd=cr

Press any key to continue . . .

私の TinyURL は google.com にリダイレクトし (ここで確認してください: http://preview.tinyurl.com/google )、ベルギーにいるので google.com は私を google.be にリダイレクトするので、これは正しいです。

于 2013-08-01T10:09:03.197 に答える