System.Net.ProtocolViolationException异常C#Post和Getresponse

时间:2013-08-12 16:49:08

标签: c# .net post

对于以下代码,我收到以下错误,

  

System.Net.ProtocolViolationException:您必须提供请求正文   如果设置ContentLength> 0或SendChunked == true。通过电话来做到这一点   [Begin] GetResponse之前[开始] GetRequestStream。

我不确定为什么会抛出此错误,任何评论或建议都会有所帮助

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

现在我修改了我的代码以使用HttpClient但不起作用,

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

        }
    }

2 个答案:

答案 0 :(得分:1)

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

  

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

您的代码调用BeginGetRequestStream,但调用GetResponse

我认为发生的是它调用BeginGetRequestStream,它启动异步写入请求流,但在主线程上它同时调用GetResponse。所以它在请求格式化之前尝试发出请求。

研究链接的MSDN主题中的示例,并相应地修改代码。

答案 1 :(得分:0)

您能考虑插入代理的可能性吗?

<system.net>
    <defaultProxy enabled="true" useDefaultCredentials="true">
      <proxy proxyaddress="http://[proxyaddress]"  bypassonlocal="True"  usesystemdefault="True" />
    </defaultProxy>
</system.net>

这适用于我的代码并解决了同样的问题,请检查您的网络。