【问题标题】:Handling the HttpWebResponse before throwing exception for (404) File Not Found在为 (404) File Not Found 引发异常之前处理 HttpWebResponse
【发布时间】:2014-07-08 17:10:40
【问题描述】:

在抛出 (404) File Not Found 异常之前,有什么方法可以处理 HttpWebResponse.GetResponse()

我有大量的图片要下载,使用 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;
    }
}

【问题讨论】:

    标签: c# asp.net download webclient httpwebresponse


    【解决方案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;
    

    【讨论】:

      【解决方案2】:

      通过发送Async 请求使用HttpClient 将解决(未找到404 文件)的异常,因此我将其视为此问题的答案,但是,我想在这里分享我的性能测试。我已经测试了以下两种方法来下载 50,000 张图片:

      方法一

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

      方法二

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

      在我的测试中,50000 张图片中有 144 张无法下载,方法 1 的性能比方法 2 快 3 倍。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-12
        • 1970-01-01
        • 1970-01-01
        • 2012-12-22
        • 1970-01-01
        • 2014-03-22
        • 1970-01-01
        相关资源
        最近更新 更多