Search code examples
c#httpwebrequesthttplistener

POSTing httpWebRequest to HttpListener


I'm starting to implement a basic C# server which will handle POSTs and GETs.

I have the following:

private static HttpListener listener;

private static void CreateListener()
{
    listener = new HttpListener();
    listener.Prefixes.Add("http://localhost:1234/");
    listener.Start();
    listener.BeginGetContext(Process, listener);
    Console.WriteLine("Listening...");
}
private static void Process(IAsyncResult result)
{
    HttpListenerContext context = listener.EndGetContext(result);
    listener.BeginGetContext(Process, listener);
    Console.WriteLine(context);
    Console.ReadLine();
}

Tried to test it with a basic httpWebRequest:

private static void Post(string webAddress)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddress);
    httpWebRequest.ContentType = "application/json; charset=utf-8";
    httpWebRequest.Method = "POST";
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = new JavaScriptSerializer().Serialize("Some POSTed Data");
        streamWriter.Write(json);
        streamWriter.Flush();
    }
}
public static void Main(string[] args)
{
    CreateListener();
    Post("http://localhost:1234/");
    Console.WriteLine("Got here!!");
    Console.ReadLine();
}

But it doesn't seem to trigger the Process function. Why is that?


Solution

  • You must call httpWebRequest.GetResponse() to send request to server and get response.

    You can find information about that here in MSDN