gpt4 book ai didi

.net - 读取 WebException 的响应流时出现 WebException

转载 作者:可可西里 更新时间:2023-11-01 15:07:32 25 4
gpt4 key购买 nike

我正在与来自 .Net 的 Web 服务器通信。 Web 服务器抛出 500 内部服务器错误并写入详细的错误消息。

我正在尝试读取从 Web 异常收到的错误消息,但收到另一个 Web 异常。为什么抛出第二个 WebException?

try
{
var webResponse = (HttpWebResponse)webRequest.GetResponse();
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
// the next line throws a web exception
Console.WriteLine(new StreamReader(e.Response.GetResponseStream()).ReadToEnd());
}
}

最佳答案

为什么这令人惊讶?从 MSDN 尝试以下方法:

try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");

// Get the associated response for the above request.
using (HttpWebResponse myHttpWebResponse =
(HttpWebResponse) myHttpWebRequest.GetResponse()) {
myHttpWebResponse.Close();
}
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"\n\nException Message :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
var response = ((HttpWebResponse)e.Response);
Console.WriteLine("Status Code : {0}", response.StatusCode);
Console.WriteLine("Status Description : {0}", response.StatusDescription);

try {
using (var stream = response.GetResponseStream()) {
using (var reader = new StreamReader(stream)) {
var text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
} catch (WebException ex) {
// Oh, well, we tried
}
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}

关于.net - 读取 WebException 的响应流时出现 WebException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1167913/

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