HttpWebRequest wait for second async response

60 Views Asked by At

So I need to get two responses from a request. The documentation from de webservice I need to call states that I will recieve a quick synchonous response and after that it will send me a slow second async response.

To me this seems very weird and I can't get .NET to wait/listenen/poll for the second response.

What I got is the following;

public void testCall(object sender, EventArgs e)
{
    byte[] xmlIn = Encoding.UTF8.GetBytes("my xml");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("my url");
    request.Method = "POST";
    request.ContentType = "application/xml";

    using (var dataStream = request.GetRequestStream())
    {
        dataStream.Write(xmlIn, 0, xmlIn.Length);
    }

    request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
}

private void FinishWebRequest(IAsyncResult result)
{       
    HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;

    using (var stream = response.GetResponseStream())
    {
        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        var responseString = reader.ReadToEnd();

        Debug.Write(responseString);
        Response.Write(responseString);
    }
}

Now this works for the first response.. but how do I get the second response?

1

There are 1 best solutions below

0
terrencep On

you should know, I dont think http is designed for this use case. Maybe you can consider System.Net.Sockets. But it's worth a try using StreamReader without disposing it (get rid of your using statement) and manually closing it when you want to by breaking out of an infinite loop and calling StreamReader.Close().

And if you go the infinite loop route, consider a timeout threshold and using s separate thread.