jeudi 22 mars 2018

UWP, C# - Retrieve the redirect url using HttpClient from the Headers of the Response - [HttpClient,C#]

I wanted to share this little piece of code because I did not quickly find any great documentation on this.

My needs where as follows: I had a URL lets say http://bit.ly/2pwccfo and I did not have the direct access to the image of the URL.  So I ended up creating a small static class that holds a method GetRedirectedUrl that will get my redirect url.

Here is my code:

public static class CoreTools
{
       public static async Task<string> GetRedirectedUrl(string url)
        {
            //this allows you to set the settings so that we can get the redirect url
            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            string redirectedUrl = null;


            using (HttpClient client = new HttpClient(handler))
            using (HttpResponseMessage response = await client.GetAsync(url))
            using (HttpContent content = response.Content)
            {
                // ... Read the StatusCode in the response 
                // to see if we have the redirected url
                if (response.StatusCode == System.Net.HttpStatusCode.Found)
                {
                    HttpResponseHeaders headers = response.Headers;
                    // do we have headers 
                    //do we have something in location
if (headers != null && headers.Location != null) { redirectedUrl = headers.Location.AbsoluteUri; } } } return redirectedUrl; } }

You can find my gist here.
Happy Coding