I’m trying to get an AWS example (from their website) working, and am getting the following error;
System.Net.ProtocolViolationException: ‘You must write ContentLength
bytes to the request stream before calling [Begin]GetResponse.’
on this line of code;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
in this function;
public static void CheckResponse(HttpWebRequest request)
{
Console.WriteLine("\n-- CHECK RESPONCE");
// Get the response and read any body into a string, then display.
Console.WriteLine(request.ContentLength); //857
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("\n-- HTTP call succeeded");
var responseBody = ReadResponseBody(response);
if (!string.IsNullOrEmpty(responseBody))
{
Console.WriteLine("\n-- Response body:");
Console.WriteLine(responseBody);
}
}
else
Console.WriteLine("\n-- HTTP call failed, status code: {0}", response.StatusCode);
}
}
request.ContentLength is 857, so am not sure how this error makes any sense. I tried setting the request.ContentLength to 857 but that causes an error.
Below is the function that calls CheckResponse()
public static void InvokeHttpRequest(Uri endpointUri,
string httpMethod,
IDictionary<string, string> headers,
string requestBody)
{
try
{
var request = ConstructWebRequest(endpointUri, httpMethod, headers);
if (!string.IsNullOrEmpty(requestBody))
{
var buffer = new byte[8192]; // arbitrary buffer size
var requestStream = request.GetRequestStream();
using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
{
var bytesRead = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
}
}
CheckResponse(request);
}
catch (WebException ex)
{
Console.WriteLine(ex.ToString());
using (var response = ex.Response as HttpWebResponse)
{
if (response != null)
{
var errorMsg = ReadResponseBody(response);
Console.WriteLine("\n-- HTTP call failed with exception '{0}', status code '{1}'", errorMsg, response.StatusCode);
}
}
}
}
>Solution :
Based on very quick scan of the code – looks like you aren’t flushing the requestStream. Wrap it in using block to ensure it is flushed.
var requestStream = request.GetRequestStream();
should be
using(var requestStream = request.GetRequestStream()) ....
The bytes aren’t necessarily written until the stream is disposed or manually flushed.