简体   繁体   English

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

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

I am using the HttpWebRequest method in the .Net Micro Framework. 我在.Net Micro Framework中使用HttpWebRequest方法。 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. “ System.Net.ProtocolViolationException:HTTP方法不正确:GET”错误。

StackTrace: 堆栈跟踪:

System.Net.HttpWebRequest::ValidateGetRequestStream System.Net.HttpWebRequest::GetRequestStream 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 ? 这个异常是否告诉我在进行POST时正在进行GET操作? If so, I have request.Method = "POST" so what would be causing it to use 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();

That exception is documented in HttpWebRequest.GetRequestStream() : HttpWebRequest.GetRequestStream()记录了该异常:

The Method property is GET or HEAD. Method属性是GET或HEAD。

So, simply set the Method to "POST" before calling GetRequestStream() . 因此,只需调用GetRequestStream() 之前将Method设置为“ POST”即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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