【发布时间】:2021-05-18 16:16:18
【问题描述】:
我正在尝试访问远程 API,但在 HTTPWebResponse 调用期间遇到了一些异常。以下是我的代码:
//url
string responseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.someapi.com")
request.Method = "GET";
request.UseDefaultCredentials = true;
request.ContentType = "application/json; charset=utf-8";
request.Headers("x-ms-client-id", "data");
try{
using (var response = (HttpWebRequest)req.GetResponse()){ <--- this line is the one that fails. System.IO.IOException here.
using (var stream = response.GetResponseStream()){
using(var sr = new StreamReader(stream)){
responseValue = sr.ReadToEnd();
}
}
}
} catch ///catch
我得到的错误是 SocketExceptions 和 WebExceptions。我不确定为什么这个特定的调用失败了。当我在 Postman 中尝试相同的 URL 和标头时,调用返回 200。
任何想法都将不胜感激。
编辑:
添加我收到的错误消息。尝试响应时抛出的异常是
System.IO.IOException: "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
【问题讨论】:
-
你得到的完整错误信息是什么?
-
这是您调用 api 的代码选择,还是您使用的是旧版本的 .NET Framework?
-
使用
HttpClient..这个WebRequest的东西是老派的。 -
是的,这是调用 API。该项目的目标是 4.5.2 .net 框架。
-
你应该在 uri 中命名方案。大概是您对 https 端点进行了 http 调用。而 HttpClient 存在于 4.5 框架中。