HttpWebRequest not posting

As per the question, I POST json to http but I'm not getting any output when I use GET.

I'm trying to POST json then close the stream. I do not need to care about the reply. To check if my POST is working, I've writtenGET.

Below is my code for POST.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:1234/xxxxx/xxxx");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{   
    string eventData = "temp string";
    string jsonEvent = JsonConvert.SerializeObject(eventData, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented });
    streamWriter.Write(jsonEvent);
}

var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); //getting "The remote server returned an error:" here
using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Below is my code for GET which I got from msdn.

WebRequest request = WebRequest.Create("http://localhost:1234/xxxxx/xxxx");
WebResponse response = request.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
reader.Close();
response.Close();
Jon Skeet
people
quotationmark

You're never asking for a response, so it's not making the request. Just add:

using (var response = request.GetResponse())
{
    // Use the response
}

Note that your "get" code isn't exception-safe - it should use using statements instead of calling Close explicitly.

people

See more on this question at Stackoverflow