我在restsharp客户端发现了一些性能问题,我在函数PerformanceRequest2中使用RestSharp向一些非常好的API发送请求,并在PerformRequest中使用WebRequest使用普通的.net请求
PerformRequest的平均响应时间是75毫秒,而使用RestSharp的PerformRequest2是300毫秒。这是restsharp的一些限制,还是我们使用restsharp
的方式做错了什么private static void PerformRequest2(string requestData)
{
var request = JsonConvert.DeserializeObject<ComplexClass>(requestData);
var client2 = new RestClient("URL");
var restRequest = new RestRequest();
restRequest.Method = Method.PUT;
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddHeader("Authorization", string.Format("Bearer {0}", token));
restRequest.AddJsonBody(request);
var restResponse2 = client2.Execute(restRequest);
if (restResponse2.StatusCode != HttpStatusCode.OK)
{
throw new Exception("error");
}
}
private static void PerformRequest(string requestData)
{
var request = JsonConvert.DeserializeObject<ComplexClass>(requestData);
var webRequest =
WebRequest.Create("URL");
webRequest.ContentType = "application/json";
webRequest.Method = "PUT";
webRequest.Headers.Add(HttpRequestHeader.Authorization, string.Format("Bearer {0}", token));
using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(request));
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse) webRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
if (string.IsNullOrEmpty(result))
{
throw new Exception("error");
}
}
}
答案 0 :(得分:5)
我从以下链接得到了答案:
http://romikoderbynew.com/2012/01/17/slow-httpwebrequest-getresponse/
应用修复
后,使用restsharp和httpwebrequest的性能相当