System.Net.ProtocolViolationException异常C#邮政GETRESPONSE [英] System.Net.ProtocolViolationException Exception C# Post and Getresponse

查看:2096
本文介绍了System.Net.ProtocolViolationException异常C#邮政GETRESPONSE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于低于code我收到以下错误,

  

System.Net.ProtocolViolationException:你必须提供一个请求主体   如果设置CONTENTLENGTH> 0或SendChunked ==真。通过调用执行此操作   前[开始] GetRequestStream [开始]的GetResponse。

我不知道为什么这个错误被抛出,有任何意见或建议将是有益

  HttpWebRequest的要求=(HttpWebRequest的)WebRequest.Create(HTTP://);

                 //设置ContentType属性。
                 request.ContentType =应用/的X WWW的形式urlen codeD;
                 //方法属性设置为POST将数据发布到URI。
                 request.Method =POST;
                 request.KeepAlive = TRUE;
                 字节[]的字节数组= Encoding.UTF8.GetBytes(POSTDATA);
                 request.ContentLength = byteArray.Length;
                 //启动异步操作。
                 request.BeginGetRequestStream(新的AsyncCallback(ReadCallback),请求);

                 //保持主线程继续,而异步
                 //操作完成。一个真正的世界中的应用
                 //可以做一些为更新其用户界面非常有用,例如。
                 allDone.WaitOne();

                 //得到响应。
                 HttpWebResponse响应=(HttpWebResponse)request.GetResponse();
                 流streamResponse = response.GetResponseStream();
                 StreamReader的streamRead =新的StreamReader(streamResponse);
                 字符串responseString = streamRead.ReadToEnd();
                 Console.WriteLine(responseString);
                 到Console.ReadLine();
                 //关闭流对象。
                 streamResponse.Close();
                 streamRead.Close();

                 //释放HttpWebResponse。
                 response.Close();





    私有静态无效ReadCallback(IAsyncResult的asynchronousResult)
    {

        HttpWebRequest的要求=(HttpWebRequest的)asynchronousResult.AsyncState;

        //结束该操作。
        流postStream = request.EndGetRequestStream(asynchronousResult);



        //将字符串转换成字节数组。
        字节[]的字节数组= Encoding.UTF8.GetBytes(POSTDATA);

        //写入请求流。
        postStream.Write(字节数组,0,postData.Length);
        postStream.Close();
        allDone.Set();
    }
 

现在我修改了code使用HttpClient的,但不能正常工作,

 公共静态异步无效PostAsync(字符串POSTDATA)
    {

        尝试
        {
            //创建一个新的HttpClient对象。
            HttpClient的客户端=新的HttpClient();

            HTT presponseMessage响应=等待client.PostAsync(HTTP://,新的StringContent(POSTDATA));
            Console.WriteLine(响应);
            //response.EnsureSuccessStatus$c$c();
            字符串responseBody =等待response.Content.ReadAsStringAsync();
            //以上三条线路可以与新的辅助方法,以下行取代
            //绳体=等待client.GetStringAsync(URI);

            Console.WriteLine(responseBody);

        }
        赶上(Htt的prequestException E)
        {
            Console.WriteLine(\ n异常捕获!);
            Console.WriteLine(消息:{0},e.Message);

        }
    }
 

解决方案

最有可能的错误是由于你混合异步和同步操作。文档 HttpWebRequest.BeginGetRequestStream 说:

  

您的应用程序不能混用同步和异步方法,特定的请求。如果调用BeginGetRequestStream方法,必须使用BeginGetResponse方法来检索响应。

您code调用 BeginGetRequestStream ,但它会调用的GetResponse

我认为正在发生的事情是,它会调用 BeginGetRequestStream ,这将启动异步写入请求流,但在主线程中调用的GetResponse 兼任。所以它的企图让请求中的请求被格式化之前

研究中的链接MSDN主题的例子,并相应修改code。

For the below code I am getting following error,

System.Net.ProtocolViolationException: You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.

I am not sure why this error is thrown, any comments or suggestions would be helpful

                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://");

                 // Set the ContentType property. 
                 request.ContentType = "application/x-www-form-urlencoded";
                 // Set the Method property to 'POST' to post data to the URI.
                 request.Method = "POST";
                 request.KeepAlive = true;
                 byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                 request.ContentLength = byteArray.Length;
                 // Start the asynchronous operation.    
                 request.BeginGetRequestStream(new AsyncCallback(ReadCallback), request);

                 // Keep the main thread from continuing while the asynchronous
                 // operation completes. A real world application
                 // could do something useful such as updating its user interface. 
                 allDone.WaitOne();

                 // Get the response.
                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                 Stream streamResponse = response.GetResponseStream();
                 StreamReader streamRead = new StreamReader(streamResponse);
                 string responseString = streamRead.ReadToEnd();
                 Console.WriteLine(responseString);
                 Console.ReadLine();
                 // Close the stream object.
                 streamResponse.Close();
                 streamRead.Close();

                 // Release the HttpWebResponse.
                 response.Close();





    private static void ReadCallback(IAsyncResult asynchronousResult)
    {

        HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

        // End the operation.
        Stream postStream = request.EndGetRequestStream(asynchronousResult);



        // Convert the string into a byte array.
        byte[] byteArray = Encoding.UTF8.GetBytes(postData);

        // Write to the request stream.
        postStream.Write(byteArray, 0, postData.Length);
        postStream.Close();
        allDone.Set();
    }

Now I modified my code for using HttpClient but does not work,

    public static async void PostAsync(String postData)
    {

        try
        {
            // Create a New HttpClient object.
            HttpClient client = new HttpClient();

            HttpResponseMessage response = await client.PostAsync("http://", new StringContent(postData));
            Console.WriteLine(response);
            //response.EnsureSuccessStatusCode();
            string responseBody = await response.Content.ReadAsStringAsync();
            // Above three lines can be replaced with new helper method in following line 
            // string body = await client.GetStringAsync(uri);

            Console.WriteLine(responseBody);

        }
        catch (HttpRequestException e)
        {
            Console.WriteLine("\nException Caught!");
            Console.WriteLine("Message :{0} ", e.Message);

        }
    }

解决方案

Most likely the error is due to you mixing asynchronous and synchronous operations. Documentation for HttpWebRequest.BeginGetRequestStream says:

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the BeginGetRequestStream method, you must use the BeginGetResponse method to retrieve the response.

Your code calls BeginGetRequestStream, but it calls GetResponse.

What I think is happening is that it calls BeginGetRequestStream, which starts the asynchronous writing to the request stream, but on the main thread it calls GetResponse concurrently. So it's attempting to make the request before the request is formatted.

Study the example in the linked MSDN topic and modify your code accordingly.

这篇关于System.Net.ProtocolViolationException异常C#邮政GETRESPONSE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆