Write length in StreamWriter

0

Good morning. I am trying through WebRequest to send a json using the PUT method. When I get to httpWebRequest.GetResponse () I get an error.

  

You must write ContentLength bytes in the request flow before calling [Begin] GetResponse.

Writing the length property to the StreamWriter as in the posotion property gives me an exception.

  

'(writer.BaseStream) .length' produced an exception of type 'System.NotSupportedException'   '(writer.BaseStream) .position' produced an exception of type 'System.NotSupportedException'

How could I fill in the length and position.

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = metodo.ContentType;

httpWebRequest.Method = WebRequestMethods.Http.Put;
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = jsSerializer.Serialize(datosPUT);
byte[] arrData = Encoding.UTF8.GetBytes(jsonData);

httpWebRequest.ContentLength = arrData.Length;
httpWebRequest.Expect = "application/json";

StreamWriter writer = new StreamWriter(httpWebRequest.GetRequestStream());
writer.Write(arrData);
writer.Close()
var response = (HttpWebResponse)httpWebRequest.GetResponse(); //AQUÍ EL ERROR
    
asked by Borja Calvo 21.09.2016 в 11:00
source

1 answer

1

Because of the error it gives you, it looks like you are not finishing flush in the stream before calling GetResponse, try writing the code like this:

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
httpWebRequest.ContentType = metodo.ContentType;

httpWebRequest.Method = WebRequestMethods.Http.Put;
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = jsSerializer.Serialize(datosPUT);
byte[] arrData = Encoding.UTF8.GetBytes(jsonData);

httpWebRequest.ContentLength = arrData.Length;
httpWebRequest.Expect = "application/json";
using (var dataStream = httpWebRequest.GetRequestStream())
{
   dataStream.Write(arrData, 0, arrData.Length);
}
var response = (HttpWebResponse)httpWebRequest.GetResponse();

Using using you ensure that the stream closes correctly.

Similar question in the English version

    
answered by 21.09.2016 / 12:15
source