2

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

        }
    }
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
Karna Desai
  • 61
  • 1
  • 9
  • 2
    You're defeating the purpose of async by sleeping until it's finished. You should make your code actually asynchronous. Consider using `Task`s. – SLaks Aug 12 '13 at 16:50
  • Better yet, switch to `HttpClient`. – SLaks Aug 12 '13 at 16:51
  • possible duplicate of [Copying Http Request InputStream](http://stackoverflow.com/questions/3447589/copying-http-request-inputstream) – Liam Aug 12 '13 at 16:51
  • How are you setting the "postData" variable? in the ReadCallBack method? – broguyman Aug 12 '13 at 17:42
  • I am setting value of postData variable before invoking POST Http requst – Karna Desai Aug 12 '13 at 17:49
  • I have modified my code for using HttpClient, but it goes into infinite wait state and the Http Post request is not being invoked – Karna Desai Aug 12 '13 at 17:50
  • Are you really trying to get from `"http://"`? Or is that just there as an example? Your problem might be related to the special status of `async void` methods. See http://stackoverflow.com/q/12144077/56778 – Jim Mischel Aug 13 '13 at 00:02
  • Which server are you making the requests to? (IIS, Apache etc.) – kerem Apr 29 '15 at 07:35

2 Answers2

1

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.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
0

Can you consider the possibility for inserted a proxy?

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

This works for my code and resolved the same issue, check in your net.

wphonestudio
  • 207
  • 2
  • 2