我有一个用于测试网络服务的小工具。
它可以使用 POST 或 GET 调用 Web 服务。
使用POST的代码是
public void PerformRequest()
{
WebRequest webRequest = WebRequest.Create(_uri);
webRequest.ContentType = "application/ocsp-request";
webRequest.Method = "POST";
webRequest.Credentials = _credentials;
webRequest.ContentLength = _request.Length;
((HttpWebRequest)webRequest).KeepAlive = false;
using (Stream st = webRequest.GetRequestStream())
st.Write(_request, 0, _request.Length);
using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse())
using (Stream responseStream = httpWebResponse.GetResponseStream())
using (BufferedStream bufferedStream = new BufferedStream(responseStream))
using (BinaryReader reader = new BinaryReader(bufferedStream))
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
throw new WebException("Got response status code: " + httpWebResponse.StatusCode);
byte[] response = reader.ReadBytes((int)httpWebResponse.ContentLength);
httpWebResponse.Close();
}
}
使用GET的代码是:
protected override void PerformRequest()
{
WebRequest webRequest = WebRequest.Create(_uri + "/" + Convert.ToBase64String(_request));
webRequest.Method = "GET";
webRequest.Credentials = _credentials;
((HttpWebRequest)webRequest).KeepAlive = false;
using (HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse())
using (Stream responseStream = httpWebResponse.GetResponseStream())
using (BufferedStream bufferedStream = new BufferedStream(responseStream))
using (BinaryReader reader = new BinaryReader(bufferedStream))
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
throw new WebException("Got response status code: " + httpWebResponse.StatusCode);
byte[] response = reader.ReadBytes((int)httpWebResponse.ContentLength);
httpWebResponse.Close();
}
}
正如您所看到的,代码非常相似。如果有的话,我预计 GET 方法会稍微慢一些,因为它必须以 Base64 编码和传输数据。
但是当我运行它时,我发现 POST 方法比 GET 方法使用更多的处理能力。在我的机器上,我可以使用大约 5% 的 CPU 运行 80 个线程的 GET 方法,而运行 80 个线程的 POST 方法使用 95% 的 CPU。
使用 POST 是否有本质上更昂贵的地方?我可以做些什么来优化 POST 方法吗?我无法重用该连接,因为我想模拟来自不同客户端的请求。
dotTrace 报告称,使用 POST 时,65% 的处理时间花费在 webRequest.GetResponse() 上。
底层 Web 服务使用摘要式身份验证(如果有任何区别)。
最佳答案
嗯,根据最终 uri 的复杂性,可能会缓存“GET”请求?默认情况下,“POST”不会被缓存,但“GET”通常会被缓存(因为它应该是幂等的)。您是否尝试过嗅探这里是否有任何差异?
此外 - 您可能会发现 WebClient
更易于使用 - 例如:
using (WebClient wc = new WebClient())
{
byte[] fromGet = wc.DownloadData(uriWithData);
byte[] fromPost = wc.UploadData(uri, data);
}
关于c# - 使用 POST 的 HttpWebRequest 的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/416306/