C # WebClient OpenRead url

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

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 don’t understand anything: when I do client.OpenRead("http://tinyurl.com/345yj7x");, does it load the page that the URL points to? If this method loads the page, I need something to get only the url, so if there is a way to get only some headers or just the url, please let me know.

+3
source share
2 answers

HEAD, :

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
}
+11

HttpWebRequest AllowAutoRedirect false, Location .

var request = (HttpWebRequest) WebRequest.Create("http://tinyurl.com/345yj7x");
request.AllowAutoRedirect = false;
var response = request.GetResponse();
var location = response.Headers[HttpResponseHeader.Location];
+1

Source: https://habr.com/ru/post/1781630/


All Articles