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

我正在使用下面的代码通过 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.WebException


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


动漫人物
浏览 325回答 1
1回答

BIG阳

当我注意到响应没有被处理时,我正在调整问题以演示对内存流的读取。这有 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.  }}
打开App,查看更多内容
随时随地看视频慕课网APP