2

I can download a page from a website using

sString = new System.Net.WebClient().DownloadString(Page);

But if the page redirects, how can I capture the new address. For example, if I fetch google.com website, I would like to grab the page it redirects to so I can get the ei code.

MiscellaneousUser
  • 2,915
  • 4
  • 25
  • 44

2 Answers2

3

Here's how it's done using HttpClient

        string Page = "https://stackoverflow.com/questions/44980231/";
        HttpClientHandler ClientHandler = new HttpClientHandler();
        ClientHandler.AllowAutoRedirect = false;
        HttpClient client = new HttpClient(ClientHandler);
        HttpResponseMessage response = await client.GetAsync(Page);
        try
        {
            string location = response.Headers.GetValues("Location").FirstOrDefault();
            if (!Uri.IsWellFormedUriString(location, UriKind.Absolute))
            {
                Uri PageUri = new Uri(Page);
                location = PageUri.Scheme + "://" + PageUri.Host + location;
            }
            MessageBox.Show(location);
        }
        catch
        {
            MessageBox.Show("No redirect!");
        }

Result:

Result

Poootaatoooo
  • 316
  • 1
  • 10
2

You need to examine the HTTP status contained in the HTTP response, and if it is an HTTP "302 Found", then you need to obtain the value of the "Location" header from the response. The value will be the target of the redirection, so you then need to download the target.

String content;
try
{
    content = new System.Net.WebClient().DownloadString( page );
}
catch( WebException e )
{
    HttpWebResponse response = (System.Net.HttpWebResponse)e.Response;
    ... examine status, get headers, etc ...
}
Mike Nakis
  • 56,297
  • 11
  • 110
  • 142