C# 使用POST的HttpWebRequest性能
我有一个用于测试Web服务的小工具 它可以使用POST或GET调用Web服务 使用POST的代码是C# 使用POST的HttpWebRequest性能,c#,.net,performance,post,httpwebrequest,C#,.net,Performance,Post,Httpwebrequest,我有一个用于测试Web服务的小工具 它可以使用POST或GET调用Web服务 使用POST的代码是 public void PerformRequest() { WebRequest webRequest = WebRequest.Create(_uri); webRequest.ContentType = "application/ocsp-request"; webRequest.Method = "POST"; webRequest.Credentials = _cred
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运行GET方法的80个线程,而POST方法的80个线程使用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);
}
是,POST定义为更改服务器状态,而GET不更改