【问题标题】:HttpWebRequest.GetResponse methods throws 404 exceptionHttpWebRequest.GetResponse 方法抛出 404 异常
【发布时间】:2015-06-03 07:18:20
【问题描述】:

我想使用控制台应用程序从 url 下载一张图片。

我使用了以下代码:

string sourceUrl = "http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg"; // Not Found
                //string sourceUrl = "http://i.ytimg.com/vi/OrxZAN1FZUY/default.jpg"; // Found
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sourceUrl);
                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (Exception)
                {

                }

以上代码在“response = (HttpWebResponse)request.GetResponse();”行中抛出异常

但是当我在浏览器中访问“http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg”网址时,将显示图像。

我在这里缺少什么?

【问题讨论】:

    标签: c# asp.net web-applications


    【解决方案1】:

    我在 Chrome 中尝试了那个网址“http://i.ytimg.com/vi/pvBnYBsUi9A/default.jpg” 开发者工具。它还会收到 404,但响应中包含显示的图像。

    您的代码不是异常的原因。网站返回 404 并且您的代码出现异常。

    您可以编写逻辑来查看响应,即使您收到 404 并决定是否接受它,就像浏览器一样。

    如果您捕获 WebException,您似乎可以获得站点返回的响应,这使您可以根据文档查看 http 请求状态和响应。

    .Net 4.5 文档中的示例...

    try 
          { 
                // Creates an HttpWebRequest for the specified URL. 
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
                // Sends the HttpWebRequest and waits for a response.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
                if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
                   Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}",
                                        myHttpWebResponse.StatusDescription);
                // Releases the resources of the response.
                myHttpWebResponse.Close(); 
    
            } 
        catch(WebException e) 
           {
                Console.WriteLine("\r\nWebException Raised. The following error occured : {0}",e.Status); 
           }
        catch(Exception e)
        {
            Console.WriteLine("\nThe following Exception was raised : {0}",e.Message);
    

    WebException 具有 Response 和 Status 属性。所以看起来 .Net 处理这个问题的方法是捕获 WebException 并根据状态和响应内容(如果需要)确定如何处理。

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多