为了账号安全,请及时绑定邮箱和手机立即绑定

获取远程服务器返回错误:(504) WebAPI 网关超时

获取远程服务器返回错误:(504) WebAPI 网关超时

C#
动漫人物 2022-07-23 16:27:14
我正在使用下面的代码通过 WebRequest 从我的 C# 代码进行 API 调用:public object GetData() { object response = ""; string token = "EF232354"; string baseUrl = ConfigurationManager.AppSettings["BaseURL"].ToString(); string endPoint = ConfigurationManager.AppSettings["EndPoint"].ToString(); var httpWebRequest = (HttpWebRequest) WebRequest.Create(baseUrl + endPoint); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = HttpVerb.GET.ToString(); httpWebRequest.Headers.Add("token", token); var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse(); Stream dataStream = httpResponse.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); using(JsonReader sdr = new JsonTextReader(reader))  {  JsonSerializer serializer = new JsonSerializer();  response = serializer.Deserialize(sdr); }  return response;}有时我会得到:消息:远程服务器返回错误:(504)网关超时。异常类型:System.Net.WebExceptionWebRequest 一次可以发出多少个请求?
查看完整描述

1 回答

?
BIG阳

TA贡献1859条经验 获得超6个赞

当我注意到响应没有被处理时,我正在调整问题以演示对内存流的读取。这有 95% 可能是您的潜在问题。Streams 和 StreamReaders 也是一次性的,应该使用 using() 闭包进行包装。


public object GetData() 

{

  object response = "";

  string token = "EF232354";

  string baseUrl = ConfigurationManager.AppSettings["BaseURL"].ToString();

  string endPoint = ConfigurationManager.AppSettings["EndPoint"].ToString();


  var httpWebRequest = (HttpWebRequest) WebRequest.Create(baseUrl + endPoint);


  httpWebRequest.ContentType = "application/json";

  httpWebRequest.Method = HttpVerb.GET.ToString();

  httpWebRequest.Headers.Add("token", token);


  using (var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse())

  {

    using (Stream dataStream = httpResponse.GetResponseStream())

    {

      using (StreamReader reader = new StreamReader(dataStream))

      {

        using(JsonReader sdr = new JsonTextReader(reader)) 

        {

          JsonSerializer serializer = new JsonSerializer();

          response = serializer.Deserialize(sdr);

        }

        return response;

      }

    }

    httpResponse.Close(); // For good measure. *should* be covered by Dispose.

  }

}


查看完整回答
反对 回复 2022-07-23
  • 1 回答
  • 0 关注
  • 324 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信