【问题标题】:System.Net.ProtocolViolationException Exception C# Post and GetresponseSystem.Net.ProtocolViolationException 异常 C# Post 和 Getresponse
【发布时间】:2013-08-12 16:49:07
【问题描述】:

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

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

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

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

        }
    }

【问题讨论】:

  • 你正在通过休眠直到它完成来打败异步的目的。您应该使您的代码实际上是异步的。考虑使用Tasks。
  • 更好的是,切换到HttpClient
  • 如何设置“postData”变量?在 ReadCallBack 方法中?
  • 我在调用 POST Http 请求之前设置 postData 变量的值

标签: c# .net post


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 2021-01-08
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多