Reputation: 959
I want to check if an given URL a is link to http://youtube.com
.
I know there are lots of various shortened version's of the links (e.g. http://youtu.be
), so what I am after is a way to resolve the URL and see if it ends up as http://youtube.com
.
A couple of example inputs are:
http://www.youtube.com/v/[videoid]
http://www.youtu.be/watch?v=[videoid]
Does anyone know of a way to do this?
Upvotes: 0
Views: 3948
Reputation: 1409
bool isYoutube = false;
string host = new Uri(url).Host;
if (host == "youtube.com" || host == "youtu.be")
{
isYoutube = true;
}
Upvotes: 2
Reputation: 25693
If you want to know whether a given URL redirects (using status codes 301
/302
) to an YouTube URL, you may either use WebClient
/HttWebRequest
/whatever directly and check the response, or disable HttpWebRequest.AllowAutoRedirect
and traverse all redirects manually (checking the status code and then the Location
HTTP header).
Upvotes: 0
Reputation: 65077
You could perform a HEAD
request:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.youtu.be/Ddn4MGaS3N4");
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
Console.WriteLine("Does this resolve to youtube?: {0}", response.ResponseUri.ToString().Contains("youtube.com") ? "Yes" : "No");
}
Appears to work fine. Unsure of edge cases but seems to do the job.
(Note: No error checking here such as 404 errors, etc).
Upvotes: 3
Reputation: 48096
First you may have to check what the hostname is for youtube (I'm just assuming it is http://youtube.com) but after you have that the following code will do what you want;
using System.Net;
IPHostEntry host = Dns.Resolve(theInputHostName);
if (host.HostName == "http://youtube.com")
// it resolves to youtube, do something.
Upvotes: 1