如何在C#中使用HttpWebRequest正确发布数据

时间:2015-01-29 12:18:04

标签: c# .net-micro-framework netduino

我在.Net Micro Framework中使用HttpWebRequest方法。我试图使用下面的方法将数据发布到另一台服务器。我得到以下内容:

例外:

" System.Net.ProtocolViolationException:HTTP方法不正确:GET"错误。

堆栈跟踪:

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

这个例外是否告诉我,当我要进行POST时,我正在进行GET?如果是这样,我有请求。方法=" POST"那么是什么原因导致它使用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();

2 个答案:

答案 0 :(得分:2)

该例外是documented in HttpWebRequest.GetRequestStream()

  

Method属性是GET或HEAD。

因此,只需将方法设置为" POST" 之前调用GetRequestStream()

答案 1 :(得分:1)

要发布,请随意使用以下代码:

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

现在,如果您需要验证并从服务器获取答案或状态:

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