2014-07-08 123 views
0

有沒有辦法拋出異常的(404)之前處理HttpWebResponse.GetResponse()文件沒有發現?處理拋出異常的(404)前的HttpWebResponse文件未找到

我有一個龐大的圖像量下載,並使用在try..catch處理未發現會讓表現非常糟糕文件的例外。

private bool Download(string url, string destination) 
{ 
    try 
    { 
      if (RemoteFileExists("http://www.example.com/FileNotFound.png") 
      { 
        WebClient downloader = new WebClient(); 
         downloader.DownloadFile(url, destination); 
         return true; 
      } 
    } 
    catch(WebException webEx) 
    { 
    } 
    return false; 
} 

private bool RemoteFileExists(string url) 
{ 
    try 
    { 
     //Creating the HttpWebRequest 
     HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
     //Setting the Request method HEAD, you can also use GET too. 
     request.Method = "HEAD"; 
     //Getting the Web Response. 
     //Here is my question, When the image's not there, 
//the following line will throw an exception, How to avoid that? 
     HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
     //Returns TURE if the Status code == 200 
     return (response.StatusCode == HttpStatusCode.OK); 
    } 
    catch 
    { 
     //Any exception will returns false. 
     return false; 
    } 
} 

回答

1

您可以使用HttpClient,它不扔404例外:

HttpClient c = new HttpClient(); 

var resp = await c.SendAsync(new HttpRequestMessage(HttpMethod.Head, "http://www.google.com/abcde")); 

bool ok = resp.StatusCode == HttpStatusCode.OK; 
0

通過發送Async要求使用HttpClient將解決(404找不到文件)除外,所以我會將其視爲這個問題的答案,但是,我想在此分享我的性能測試。我已經測試了以下方法來下載50000張圖片:

方法1

try 
{ 
    // I will not check at all and let the the exception happens 
    downloader.DownloadFile(url, destination); 
    return true; 
} 
catch(WebException webEx) 
{ 
} 

方法2

try 
{ 
    // Using HttpClient to avoid the 404 exception 
    HttpClient c = new HttpClient(); 

    var resp = await c.SendAsync(new HttpRequestMessage(HttpMethod.Head, 
      "http://www.example.com/img.jpg")); 

    if (resp.StatusCode == HttpStatusCode.OK) 
    { 
     downloader.DownloadFile(url, destination); 
     return true; 
    } 
} 
catch(WebException webEx) 
{ 
} 

在我的測試中,144個圖像無法獲得了50.000的圖像是下載,方法1中的性能比方法2快3倍。

相關問題