首页 > 解决方案 > 如何静默绕过对失败(404 Not Found)的 webRequest.GetResponse() 的 REST 调用?

问题描述

当我传递一个可识别的参数时,我的代码可以工作,但是当我传递的参数未被识别时,我会收到一条错误消息。我不一定期望(或需要)在每种情况下都有好的回应,但是当没有结果返回给我时,我不想被异常“打扰”。

我举几个例子。如果我将它传递给 (HttpWebRequest)WebRequest (使用“tt0003854”作为参数):

https://api.themoviedb.org/3/movie/tt0003854/release_dates?api_key=Gr8GooglyMoogly&language=en-US&external_source=imdb_id

...我得到了我想要的东西:

{"id":347745,"results":[{"iso_3166_1":"US","re​​lease_dates":[{"certification":"","iso_639_1":"","note":"","re​​lease_date ":"1936-12-12T00:00:00.000Z","type":3}]}]}

其他尝试也是如此。但是,有些失败,例如当我使用“tt0005929”作为参数时:

https://api.themoviedb.org/3/movie/tt0005929/release_dates?api_key=Gr8GooglyMoogly&language=en-US&external_source=imdb_id

...返回:

{"success":false,"status_code":34,"status_message":"找不到您请求的资源。"}

它在这一行失败:

var webResponse = (HttpWebResponse)webRequest.GetResponse();

...然后落入 catch 块,此时我收到一条错误消息,上面写着“远程服务器返回错误:(404)未找到

如果找不到它是“好的”,但我不希望应用程序因错误消息而停止。我该怎么做才能忽略“404”?

这是我的更多代码,用于上下文:

try
{
    var webRequest = (HttpWebRequest)WebRequest.Create(RESTStringToGetMPAARatingForMovieId);
    webRequest.Method = "GET";  // <-- GET is the default method/verb, but it's here for clarity
    var webResponse = (HttpWebResponse)webRequest.GetResponse();
    if (webResponse.StatusCode == HttpStatusCode.NotFound)
    {
        continue; // this is not reached, even when I get the error
    }
    if ((webResponse.StatusCode != HttpStatusCode.OK) || (webResponse.ContentLength == 0))
    {
        continue; // this is not reached, either
    }
    if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
    {
        StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
        string s = streamReader.ReadToEnd();
        . . .    
    }
    else
    {   // I don't see this message
        MessageBox.Show(string.Format("Status code == {0}, Content length == {1}",
          webResponse.StatusCode, webResponse.ContentLength));
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

标签: c#http-status-code-404httpwebrequesthttpwebresponse

解决方案


第一:强制转换或方法调用是否引发错误?(只需将调用拆分并转换为两行)第二:您可以try {...} catch(Exception ex) /*{MessageBox.Show(Ex.Message)*/}在该行周围放置一个块,但是,您必须确保后面的代码即使使用错误的值也能正常工作,并确保对其进行测试。


推荐阅读