0

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

例外:

“System.Net.ProtocolViolationException:HTTP 方法不正确: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();
4

2 回答 2

2

该异常记录在HttpWebRequest.GetRequestStream()

Method 属性是 GET 或 HEAD。

因此,只需在调用之前将 Method 设置为“POST” GetRequestStream()

于 2015-01-29T12:25:21.590 回答
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();
            }
        }
    }
}
于 2015-01-29T12:27:19.900 回答