I have the following C# program:
using System;
using System.IO;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string sourceUri = "http://tinyurl.com/22m56h9";
var request = WebRequest.Create(sourceUri);
try
{
//Edit: request = WebRequest.Create(sourceUri);
request.Method = "HEAD";
var response = request.GetRespons开发者_如何学运维e();
if (response != null)
{
Console.WriteLine(request.GetResponse().ResponseUri);
}
}
catch (Exception exception) {
Console.WriteLine(exception.Message);
}
Console.Read();
}
}
}
If a run my program, with the sourceUri = "http://tinyurl.com/22m56h9" everithing is OK, i just get the destination of the tinyurl link.
But if a run my program with tinyurl link that redirects to a site that is marked as malware, my code throws an exception sayingThe remote host could not be resolved: '...'
. I need to get the uri of the malware link, because i want to make an application that search some test for link and returns if they are malware or not, and if a link is minified (the case above), i need to know where is redirecting to.
So my question is Am i doing something wrong in my code? or Is there a better aproach on testing if a link is a redirect or not? Thank in advance
Instead of a catching a general Exception you should try catching a WebException object instead. Something like:
try
{
request.Method = "HEAD";
var response = request.GetResponse();
if (response != null)
{
Console.WriteLine(request.GetResponse().ResponseUri);
}
}
catch (WebException webEx) {
// Now you can access webEx.Response object that contains more info on the server response
if(webEx.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)webEx.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)webEx.Response).StatusDescription);
}
}
catch (Exception exception) {
Console.WriteLine(exception.Message);
}
The WebException contains a Response object that you can access to find out more information about what the server actually returned.
You may be interested in reading server response codes (HTTP headers). A redirect is usually done by them.
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection
精彩评论