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

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

我正在使用 .Net Micro Framework 中的 HttpWebRequest 方法。我正在尝试使用以下方法将 post 数据传输到另一台服务器。我得到以下信息:

异常:

"System.Net.ProtocolViolationException: HTTP Method is incorrect: GET" 错误。

堆栈跟踪:

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

这个异常是否告诉我在我应该进行 POST 时进行了 GET ?如果是这样,我有 request.Method = "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();

那个例外是documented in HttpWebRequest.GetRequestStream():

The Method property is GET or HEAD.

因此,只需在 调用 GetRequestStream().

之前将方法设置为 "POST"

为了post,欢迎使用以下代码:

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