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

时间:2019-01-15 04:54:15

标签: c# asp.net-web-api webrequest

我正在使用以下代码通过WebRequest从我的C#代码进行API调用:

# Groups:   user_id [1]
 user_id page  time  duration  csum  rank
     <int> <fct> <fct>    <int> <int> <dbl>
1       1 A     12:15        5     5     1
2       1 B     12:21        3     8     1
3       1 C     12:25       22    30     2
4       1 D     12:48        5    35     2
5       1 B     12:54        2    37     2
6       1 A     12:57        5    42     2

有时候我会得到:

  

消息:远程服务器返回错误:(504)网关超时。

     

异常类型:System.Net.WebException

WebRequest一次可以发出多少个请求?

1 个答案:

答案 0 :(得分:1)

当我注意到响应未得到处理时,我正在修改问题以演示如何读取内存流。这有95%可能是您的根本问题。 Streams和StreamReader也是一次性的,应该用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.
  }
}