1

I use to send POST request and get response by this way:

response = (HttpWebResponse)request.GetResponse();

But, I just want to send request, I don't care what response is. Size of response package can be up to 500Kb ~ 1Mb, It wastes lots of time. How can I send request and then stop receive response immediately. Thanks so much!

Tiang
  • 57
  • 1
  • 11

2 Answers2

2

If your only concern is the time it takes to receive the response, and not the bandwidth being used, you could get the response asynchronously.

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetresponse.aspx

The example given is a bit complicated, but the general idea is that your program will not wait for the response to be downloaded when BeginGetResponse is called, like it would if you just called GetResponse. The first method that you pass to BeginGetResponse is the name of a method (called a "callback") that will get called when the response eventually is fully downloaded. This is where you'd put your code to check the HTTP response code, assuming you cared about that. The 2nd parameter is a "state" object that gets passed to your callback method. We'll use this to make sure everything gets cleaned up properly.

It would look something like this:

    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.
    }
Robert Dusek
  • 106
  • 5
  • If i don't need to validate reponse data, Can I unused `DownloadComplete(IAsyncResult ar)` method ? – Tiang Mar 09 '12 at 06:58
  • 1
    What I have there is probably the minimum you'd want to use. The call to request.EndGetResponse(ar) makes sure everything gets cleaned up properly. – Robert Dusek Mar 09 '12 at 07:01
0

I assume you are sending a GET request to the server. Change it to a HEAD request.

var request = System.Net.HttpWebRequest.Create("http://...");
request.Method = "HEAD";
request.GetResponse();

This will only return the length of the content. See How to get the file size from http headers for more info.

Community
  • 1
  • 1
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73