2011-01-10 27 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對象,您可以訪問,以瞭解哪些服務器實際上返回更多的信息。