C# WebClient OpenRead url

2020-07-17 16:45发布

问题:

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.

回答1:

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
}


回答2:

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];


标签: c# webclient