Search code examples
c#.net-micro-frameworknetduino

How do I properly post data using the HttpWebRequest in C#


I am using the HttpWebRequest method in the .Net Micro Framework. I am trying to post data to a another server using the method below. I am getting the following :

Exception:

"System.Net.ProtocolViolationException: HTTP Method is incorrect: GET" error.

StackTrace:

System.Net.HttpWebRequest::ValidateGetRequestStream System.Net.HttpWebRequest::GetRequestStream

Does this exception tell me that I am making a GET when I should be making a POST ? If so, I have request.Method = "POST" so what would be causing it to use GET ?

                    HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(@"http://192.168.2.1:3322/home/PostEvent");
                    Stream dataStream = webReq.GetRequestStream();

                    UTF8Encoding enc = new UTF8Encoding();
                    byte[] data = UTF8Encoding.UTF8.GetBytes(strMachineEvt.ToString());

                    dataStream.Write(data, 0, data.Length);
                    dataStream.Close();

                    webReq.Method = "POST";
                    webReq.ContentType = "application/json";
                    webReq.ContentLength = data.Length;

                    WebResponse response = webReq.GetResponse();

                    //HttpWebResponse resp = (HttpWebResponse)webReq.GetResponse();

                    Debug.Print(((HttpWebResponse)response).StatusDescription);
                    Stream respData = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);

                    string responseFromServer = reader.ReadToEnd();
                    // Display the content.
                    Debug.Print(responseFromServer);
                    // Clean up the streams.
                    reader.Close();
                    dataStream.Close();
                    response.Close();

Solution

  • That exception is documented in HttpWebRequest.GetRequestStream():

    The Method property is GET or HEAD.

    So, simply set the Method to "POST" before calling GetRequestStream().