how to use HttpListener to receive HTTP Post which contain XML how to use HttpListener to receive HTTP Post which contain XML xml xml

how to use HttpListener to receive HTTP Post which contain XML


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.