【问题标题】:HTTPWebResponse "GET" API Call Exception - C#HTTPWebResponse "GET" API 调用异常 - C#
【发布时间】: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 框架中。

标签: c# http


【解决方案1】:

通常,我经常使用HttpWebRequest,如下面的代码。

You can download the HttpHelper我按照我的参考示例编译调用,也可以根据需要添加Http Header。

如何调用 HttpHelper,例如:Get 方法

Console app to use azure storage tableapi

String PostParam = String.Empty;
if (Data != null)
{
    PostParam = Data.ToString();//Newtonsoft.Json.JsonConvert.SerializeObject(Data);
}
byte[] postData = Encoding.UTF8.GetBytes(PostParam);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url + (Id == null ? "" : '/' + Id.ToString())));
request.Method = Method;
request.ServicePoint.Expect100Continue = false;
request.Timeout = HttpRequestTimeOut;
request.ContentType = "application/json";
request.ContentLength = postData.Length;
if (postData.Length > 0)
{
    using (Stream requestStream = request.GetRequestStream())
    {
         requestStream.Write(postData, 0, postData.Length);
    }
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    Response.Code = response.StatusCode;
    using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
    {
         Response.Data = stream.ReadToEnd();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多