Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

httplistener with post data

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

like image 848
Nathan Avatar asked Dec 26 '11 17:12

Nathan


1 Answers

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
like image 57
Jon Skeet Avatar answered Oct 23 '22 10:10

Jon Skeet