2

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

System.Net.ProtocolViolationException:如果设置 ContentLength>0 或 SendChunked==true,则必须提供请求正文。通过在 [Begin]GetResponse 之前调用 [Begin]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);

        }
    }
4

2 回答 2

1

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

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

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

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

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

于 2013-08-12T21:50:58.050 回答
0

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

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

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

于 2016-06-11T17:43:33.237 回答