httplistener with post data

Nathan picture Nathan · Dec 26, 2011 · Viewed 23.3k times · Source

I'm looking at creating a small windows service that will communicate with clients via JSON. I've created a simple HttpListener sample and that's working correctly.

My question is how do i go about retrieving the JSON data from a client(POST)?

thanks

Answer

Jon Skeet picture Jon Skeet · Dec 26, 2011

When you accept a request from HttpListener, you get an HttpListenerContext. From there, you can get an HttpListenerRequest - and that has an InputStream property which you can read the data from.

To read text data (such as JSON) you can use the ContentEncoding property and build a StreamReader. For example:

var context = listener.GetContext();
var request = context.Request;
string text;
using (var reader = new StreamReader(request.InputStream,
                                     request.ContentEncoding))
{
    text = reader.ReadToEnd();
}
// Use text here