我有一个用于测试网络服务的小工具。
它可以使用 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 运行 GET 方法的 80 个线程,而 POST 方法的 80 个线程使用 95% 的 CPU。
使用 POST 有什么本质上更昂贵的东西吗?我可以做些什么来优化 POST 方法吗?我无法重用连接,因为我想模拟来自不同客户端的请求。
dotTrace 报告说,在使用 POST 时,65% 的处理时间花费在 webRequest.GetResponse() 中。
如果这有任何区别,则底层 Web 服务将使用 Digest-Authentication。