CheckingTrt
CheckingTrt

Reputation: 41

Stream does not support reading when placing a HTTP Post request

I am facing an error that is "Stream does not support reading". I am placing a Http post request to the url. Below is my code that what i am using

var request = (HttpWebRequest) WebRequest.Create("https://test.com/Hotel Hospitality Source?method=fetchInfo");

var postData = "&username=testing";
postData += "&password=Testing";
postData += "&hotelId=h075-103";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using(var ms = new MemoryStream())
request.GetRequestStream().CopyTo(ms);

var response = (HttpWebResponse) request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

Firstly I have used below code.

 using (var stream = request.GetRequestStream())
 {
     stream.Write(data, 0, data.Length);
 }

 var response = (HttpWebResponse)request.GetResponse();

 var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

enter image description here

I am getting error when I am using CopyTo method for stream. How can I resolve this error?

Upvotes: 0

Views: 24983

Answers (1)

CodeCaster
CodeCaster

Reputation: 151584

What is using (var ms=new MemoryStream()) request.GetRequestStream().CopyTo(ms); supposed to do? You're trying to copy the request stream (which is write-only) into a new memorystream that you then dispose.

You need to write into the request stream:

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

Upvotes: 6

Related Questions