how to use HttpListener to receive HTTP Post which contain XML

briswill picture briswill · Aug 10, 2011 · Viewed 30.2k times · Source

I am working on a project that will receive HTTP POSTs which contain XML data. I am going to set up HttpListener to receive HTTP POST and then response with ACK.

I am wondering if there are any examples that implement similar functionality? And how many requests could HttpListener handle in the same time?

I will have a message queue to store the requests from the client. And I will have to set up a test client to send the request to the HttpListener for testing purposes. Should I set up a WebRequest or something else to test HttpListener?

Answer

Bryan Rehbein picture Bryan Rehbein · Oct 16, 2011

You can use HttpListener to process incoming HTTP POSTs, you can pretty much follow any tutorial you find for the listener. Here is how I am doing it (note this is syncronous, to handle more than 1 request at a time, you will want to use threads or at least the async methods.)

public void RunServer()
{
    var prefix = "http://*:4333/";
    HttpListener listener = new HttpListener();
    listener.Prefixes.Add(prefix);
    try
    {
        listener.Start();
    }
    catch (HttpListenerException hlex)
    {
        return;
    }
    while (listener.IsListening)
    {
        var context = listener.GetContext();
        ProcessRequest(context);
    }
    listener.Close();
}

private void ProcessRequest(HttpListenerContext context) 
{
    // Get the data from the HTTP stream
    var body = new StreamReader(context.Request.InputStream).ReadToEnd();

    byte[] b = Encoding.UTF8.GetBytes("ACK");
    context.Response.StatusCode = 200;
    context.Response.KeepAlive = false;
    context.Response.ContentLength64 = b.Length;

    var output = context.Response.OutputStream;
    output.Write(b, 0, b.Length);
    context.Response.Close();
}

The main part that gets the XML from the request is this line:

var body = new StreamReader(context.Request.InputStream).ReadToEnd();

This give you the body of the HTTP request, which should contain your XML. You could probably send it straight into any XML library that can read from a stream, but be sure to watch for exceptions if a stray HTTP request also gets sent to your server.