我用来发送POST请求并通过这种方式获得响应:
response = (HttpWebResponse)request.GetResponse();
但是,我只是想发送请求,我不在乎是什么回应。响应包的大小可以达到500Kb~1Mb,浪费了大量的时间。如何发送请求然后立即停止接收响应。非常感谢!
答案 0 :(得分:2)
如果您唯一关心的是接收响应所需的时间,而不是正在使用的带宽,则可以异步获取响应。
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx
给出的示例有点复杂,但一般的想法是,当调用BeginGetResponse时,您的程序不会等待下载响应,就像您刚刚调用GetResponse一样。传递给BeginGetResponse的第一个方法是方法的名称(称为“回调”),当响应最终 完全下载时,将调用该方法。这是您放置代码以检查HTTP响应代码的地方,假设您关心这一点。第二个参数是一个传递给回调方法的“状态”对象。我们将使用它来确保所有内容都得到妥善清理。
它看起来像这样:
private void YourMethod()
{
// Set up your request as usual.
request.BeginGetResponse(DownloadComplete, request);
// Code down here runs immediately, without waiting for the response to download
}
private static void DownloadComplete(IAsyncResult ar)
{
var request = (HttpWebRequest)ar.AsyncState;
var response = request.EndGetResponse(ar);
// You can check your response here to make sure everything worked.
}
答案 1 :(得分:0)
我假设您正在向服务器发送GET请求。将其更改为HEAD请求。
var request = System.Net.HttpWebRequest.Create("http://...");
request.Method = "HEAD";
request.GetResponse();
这只会返回内容的长度。有关详细信息,请参阅How to get the file size from http headers。