【发布时间】:2021-04-02 17:58:48
【问题描述】:
所以我尝试在我的 Revit(BIM 软件)C# 插件中使用 HttpWebRequest,向我的 API 发送请求。但是每次我尝试这个时,它所花费的时间都比 Chrome/Firefox/Postman 中的请求要长。
如果我通过 Postman 发送请求,大约需要 1 到 1.5 秒。但如果我在我的应用程序中发送它,大约需要 21 到 21.5 秒。所以看起来HttpWebrequest创建了某种超时,但我似乎无法弄清楚为什么会这样。
我的代码:
static public string Get(string baseURI, Dictionary<string, string> requestParameters)
{
ServicePointManager.UseNagleAlgorithm = false;
ServicePointManager.DefaultConnectionLimit = 15;
string requestURI = baseURI;
if (requestURI.Length != 0)
{
foreach (KeyValuePair<string, string> parameter in requestParameters)
{
if (requestURI[requestURI.Length - 1] != '?')
{
requestURI = requestURI + '&';
}
requestURI = requestURI + parameter.Key + "=" + parameter.Value;
}
}
HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;
request.Method = "GET";
string results = string.Empty;
request.Proxy = null;
request.KeepAlive = false;
HttpWebResponse response;
using (response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
results = reader.ReadToEnd();
reader.Close();
response.Close();
}
return results;
}
我尝试了以下方法:
使用 RestSharp
使用 HttpWebRequest
发送两个请求(两个不同的请求相同),其中第二个请求只需要 1.5 秒。
我试过 request.Proxy = null; /ServicePointManager.UseNagleAlgorithm = false; /request.KeepAlive/ServicePointManager.DefaultConnectionLimit = 15;
我想不出其他任何事情,而且调试器没有给我任何有用的信息,说明它在这 20 秒内做了什么。
【问题讨论】:
-
根据支持的 .NET 版本,您最好查看
HttpClient。