4

So I have this program that fetches a page using a short link (I used Google url shortener). To build my example I used code from Using WebClient in C# is there a way to get the URL of a site after being redirected?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyWebClient client = new MyWebClient();
            client.OpenRead("http://tinyurl.com/345yj7x");            
            Uri uri = client.ResponseUri;            
            Console.WriteLine(uri.AbsoluteUri);
            Console.Read();
        }
    }

    class MyWebClient : WebClient
    {
        Uri _responseUri;

        public Uri ResponseUri
        {
            get { return _responseUri; }
        }

        protected override WebResponse GetWebResponse(WebRequest request)
        {
            WebResponse response = base.GetWebResponse(request);
            _responseUri = response.ResponseUri;
            return response;
        }
    }
}

I do not understant a thing: when I do client.OpenRead("http://tinyurl.com/345yj7x"); this downloads the page that the url points to? If this method downloads the page, I need something to get me only the url, so if there's a method to get only some headers, or only the url, please let me know.

Community
  • 1
  • 1
cristian
  • 8,676
  • 3
  • 38
  • 44

2 Answers2

11

You can get the headers only using a HEAD request, like this:

var request = WebRequest.Create(sourceUri);
request.Method = "HEAD";

var response = request.GetResponse();
if (response != null) {
    // You can now use response.Headers to get header info
}
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 1
    Bullseye. Then just use response.ResponseUri to get your URL - in this case it looks to be "http://www.google.ro/search?sourceid=chrome&ie=UTF-8&q=c%23+webclient+tinyurl" – Reddog Dec 22 '10 at 10:13
  • Added using on response otherwise you leave the connection open. https://stackoverflow.com/a/46832502/1087922 – Zunair Oct 19 '17 at 15:41
3

Create a HttpWebRequest with the AllowAutoRedirect property set to false, then look at the Location header on the response.

var request = (HttpWebRequest) WebRequest.Create("http://tinyurl.com/345yj7x");
request.AllowAutoRedirect = false;
var response = request.GetResponse();
var location = response.Headers[HttpResponseHeader.Location];
Nathan Baulch
  • 20,233
  • 5
  • 52
  • 56