Search code examples
c#winformshttpwebrequest.net-4.5httpwebresponse

Need to call method as soon as server starts responding to my HttpWebRequest


I need to call a method in new thread for ex: mymethod() as soon as server starts responding to my HttpWebRequest.

I am using below to send http requst and getting response.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(MyUrl);
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Now what i need is for my request when server starts responding as soon as i need to call a method mymethod() in new thread. But problem is I don't know how to detect that server has started responding (started responsestream ) to my request. What is the way that tell me that server started responding and I can call my method.

Target framework: is .net framework 4.5 and my project is Windows Form application.


Solution

  • The closest I can think of is using HttpClient and passing a HttpCompletionOption.ResponseHeadersRead, so you can start receiving the request once the headers are sent and later start processing the rest of the response:

    public async Task ProcessRequestAsync()
    {
        var httpClient = new HttpClient();
        var response = await httpClient.GetAsync(
               url, 
               HttpCompletionOption.ResponseHeadersRead);
    
        // When we reach this, only the headers have been read.
        // Now, you can run your method
        FooMethod();
    
        // Continue reading the response. Change this to whichever
        // output type you need (string, stream, etc..)
        var content = response.Content.ReadAsStringAsync();
    }