Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# WebClient OpenRead url

Tags:

c#

webclient

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.

like image 517
cristian Avatar asked Dec 09 '22 12:12

cristian


2 Answers

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
}
like image 189
Jon Avatar answered Dec 26 '22 08:12

Jon


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];
like image 36
Nathan Baulch Avatar answered Dec 26 '22 06:12

Nathan Baulch