gpt4 book ai didi

c# - 我怎样才能 catch 404?

转载 作者:IT王子 更新时间:2023-10-29 03:37:56 25 4
gpt4 key购买 nike

我有以下代码:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "HEAD";
request.Credentials = MyCredentialCache;

try
{
request.GetResponse();
}
catch
{
}

如何捕获特定的 404 错误? WebExceptionStatus.ProtocolError 只能检测到有错误发生,并不能给出错误的具体代码。

例如:

catch (WebException ex)
{
if (ex.Status != WebExceptionStatus.ProtocolError)
{
throw ex;
}
}

只是不够有用...协议(protocol)异常可能是 401、503、403,任何东西。

最佳答案

try
{
var request = WebRequest.Create(uri);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
// Process the stream
}
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError &&
ex.Response != null)
{
var resp = (HttpWebResponse) ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound)
{
// Do something
}
else
{
// Do something else
}
}
else
{
// Do something else
}
}

关于c# - 我怎样才能 catch 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1949610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com