2011-01-10 136 views
2

我有以下的C#程序:远程主机无法解析:

 
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.GetResponse(); 
       if (response != null) 
       { 
        Console.WriteLine(request.GetResponse().ResponseUri); 
       } 
      } 
      catch (Exception exception) { 
       Console.WriteLine(exception.Message);     
      } 
      Console.Read(); 
     } 
    }  
} 
 

如果运行我的程序,用sourceUri =“http://tinyurl.com/22m56h9” everithing是确定的,我只是得到tinyurl链接的目的地。
但是,如果使用tinyurl链接运行我的程序,并将其重定向到标记为恶意软件的站点,则我的代码将引发一个异常,说The remote host could not be resolved: '...'。我需要获取恶意软件链接的URI,因为我想制作一个应用程序,用于搜索某个链接的测试并返回它们是否为恶意软件,如果链接被缩小(上面的情况),我需要知道哪里正在重定向到。

所以我的问题是我在我的代码中做错了什么?或者如果链接是重定向或者没有更好的方法测试? 预先感谢

+1

请注意,您不需要`创建`Web请求两次。 – 2011-01-10 09:17:56

+0

好评。谢谢 – cristian 2011-01-10 09:18:49

回答

2

取而代之的是抓住你应该尝试捉住WebException对象,而不是一般的异常。喜欢的东西:

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);     
} 

将引发WebException包含Response对象,您可以访问,以了解哪些服务器实际上返回更多的信息。