C# WebClient OpenRead url

爱⌒轻易说出口 提交于 2020-01-01 14:57:52

问题


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


来源:https://stackoverflow.com/questions/4507941/c-sharp-webclient-openread-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!