aznboy84
aznboy84

Reputation: 411

How to get last url from HttpClient?

OK, i was recently switch to .NET framework 4.5 and start using HttpClient instead of HttpWebRequest & Response. I really love that async/await style but i don't know how to get the redirected url after a POST / GET request.

With HttpWebResponse i can use .ResponseUri attribute

HttpWebRequest request = (HttpWebRequest)WebRequest.Create ("http://www.google.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
string responseURI = response.ResponseUri;

Took me 3 hours of searching and i still can't get it done:(

Upvotes: 31

Views: 30696

Answers (2)

Tom Gullen
Tom Gullen

Reputation: 61719

Old question, but this is a modern update:

internal static Uri GetEndURI(Uri requestedUri)
{
    try
    {
        using (var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = true }))
        {
            client.Timeout = new TimeSpan(0, 0, 5);
            using (var response = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, requestedUri)))
            {
                var result = response.Result;
                return result.RequestMessage.RequestUri;
            }
        }
    }
    catch (Exception)
    {
        // Something went wrong
    }
}

Upvotes: 0

ermagana
ermagana

Reputation: 1230

So from the msdn articles HttpResponseMessage returns as a Task from an HttpClient call.

This HttpResponseMessage has a property called Request Message, which has a property called RequestUri, make sure to look in the properties section of this link.

Sample Code:

// Create a New HttpClient object.
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://www.yahoo.com/");
response.EnsureSuccessStatusCode();
string responseUri = response.RequestMessage.RequestUri.ToString();
Console.Out.WriteLine(responseUri);

Upvotes: 52

Related Questions