HttpWebRequest引发“远程服务器返回错误:(404)未找到。”为404

时间:2019-09-03 18:37:19

标签: c# .net httpwebrequest

我正在尝试发出网络请求:

String url = @"http://stackoverflow.com/aaaaaaaa.html";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

String responseText;

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
   if (response.StatusCode == HttpStatusCode.NotFound) //404
      return "";

   using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
   {
      responseText = responseStream.ReadToEnd();
   }
}

问题是该行:

request.GetResponse();

引发异常:

  • System.Net.HttpWebResponse
    • “远程服务器返回错误:(404)未找到。”

HttpWebRequest为什么引发异常;为什么?以及如何使它停止?

或者

有人可以建议可以让我与网络服务器对话的方法或.NET类,并检索 完全有效但并非例外 < / strong> 404。

HttpClient有自己的issues,将其从考虑中删除。

1 个答案:

答案 0 :(得分:0)

以下是我编写的一些代码,欢迎您使用该代码处理这种情况。 如果引发异常,则可以通过捕获WebException来获取状态代码。

public class WebResult
{
    public string Response { get; set; }
    public bool WasSuccessful { get; set; }
    public HttpStatusCode? StatusCode { get; set; }
}

public WebResult GetUrlContents(string url)
{
    try
    {
        var request = (HttpWebRequest)WebRequest.Create(url);

        using (var response = (HttpWebResponse)request.GetResponse())
        using (var responseStream = new StreamReader(response.GetResponseStream()))
        {
            return new WebResult
            {
                WasSuccessful = true,
                Response = responseStream.ReadToEnd(),
                StatusCode = response.StatusCode
            };
        }
    }
    catch (WebException webException)
    {
        return new WebResult
        {
            Response = null,
            WasSuccessful = false,
            StatusCode = (webException.Response as HttpWebResponse)?.StatusCode
        };
    }
}