首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用POST的HttpWebRequest性能

使用POST的HttpWebRequest性能
EN

Stack Overflow用户
提问于 2009-01-06 12:15:49
回答 1查看 7K关注 0票数 2

我有一个用于测试for服务的小工具。

它既可以使用POST调用webservice,也可以使用GET调用。

使用POST的代码是

代码语言:javascript
复制
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的代码如下:

代码语言:javascript
复制
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-方法线程,而使用95%的CPU运行80个POST方法线程。

使用POST有没有什么固有的更昂贵的东西?有什么我可以做的来优化POST方法吗?我不能重用连接,因为我想模拟来自不同客户端的请求。

dotTrace报告说,在使用POST时,65%的处理时间花费在webRequest.GetResponse()上。

底层的webservice使用Digest-Authentication,如果这有什么不同的话。

EN

回答 1

Stack Overflow用户

发布于 2009-01-06 12:41:34

那么,根据最终uri的复杂程度,可能正在缓存"GET“请求?默认情况下,"POST“不会被缓存,但"GET”通常会被缓存(因为它应该是幂等的)。你有没有试过嗅探,看看这里有没有什么不同?

此外,您可能会发现WebClient更易于使用,例如:

代码语言:javascript
复制
using (WebClient wc = new WebClient())
{
    byte[] fromGet = wc.DownloadData(uriWithData);
    byte[] fromPost = wc.UploadData(uri, data);
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/416306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档