ViolationException异常C#邮政GETRESPO

ViolationException异常C#邮政GETRESPO

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

问题描述

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

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

  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 说:

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

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

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

For the below code I am getting following error,

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 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:03