Alex Rivera | Logout

httplistener with post data

Asked 2011-12-26T17:34:21.660
15

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

Edit
Report

1 Answer

35

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
answered 2011-12-26T17:37:11.973

Your Answer