我有一个用于测试for服务的小工具。
它既可以使用POST调用webservice,也可以使用GET调用。
使用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-方法线程,而使用95%的CPU运行80个POST方法线程。
使用POST有没有什么固有的更昂贵的东西?有什么我可以做的来优化POST方法吗?我不能重用连接,因为我想模拟来自不同客户端的请求。
dotTrace报告说,在使用POST时,65%的处理时间花费在webRequest.GetResponse()上。
底层的webservice使用Digest-Authentication,如果这有什么不同的话。
发布于 2009-01-06 12:41:34
那么,根据最终uri的复杂程度,可能正在缓存"GET“请求?默认情况下,"POST“不会被缓存,但"GET”通常会被缓存(因为它应该是幂等的)。你有没有试过嗅探,看看这里有没有什么不同?
此外,您可能会发现WebClient更易于使用,例如:
using (WebClient wc = new WebClient())
{
byte[] fromGet = wc.DownloadData(uriWithData);
byte[] fromPost = wc.UploadData(uri, data);
}https://stackoverflow.com/questions/416306
复制相似问题