简体   繁体   中英

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();

That exception is documented in HttpWebRequest.GetRequestStream() :

The Method property is GET or HEAD.

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

In order to post, feel free to use the following code:

var request            = (HttpWebRequest)WebRequest.Create(Url);
byte[] byteArray       = Encoding.UTF8.GetBytes(YourParametersString);

request.Method         = WebRequestMethods.Http.Post;
request.ContentLength  = byteArray.Length;
request.ContentType    = "application/json";

Stream postStream      = request.GetRequestStream();

postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();

Now, if you need to verify and grab the answer or the status from the server:

using (var response = (HttpWebResponse)request.GetResponse()){
    var responseValue = string.Empty;

    // Error
    if (response.StatusCode != HttpStatusCode.OK){
        var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
        throw new ApplicationException(message);
    }

    // Grab the response
    using (var responseStream = response.GetResponseStream()){
        if (responseStream != null){
            using (var reader = new StreamReader(responseStream)){
                responseValue = reader.ReadToEnd();
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM