2

I have the following code:

 // Create POST data and convert it to a byte array.
 string postData = "name=t&description=tt";
 byte[] byteArray = Encoding.UTF8.GetBytes(postData);
 // Set the ContentType property of the WebRequest.
 request.ContentType = "application/x-www-form-urlencoded";
 // Set the ContentLength property of the WebRequest.
 request.ContentLength = byteArray.Length;
 // Get the request stream.
 using (StreamReader reader = new StreamReader(request.GetRequestStream()))
 {
     string s = reader.ReadToEnd();
 }

When the flow hits the using (..... ) statement, I get the following exception:

Stream was not readable

I want to read the entire request stream into a string, nothing is closed, so the code should work?

Drew Noakes
  • 300,895
  • 165
  • 679
  • 742
GurdeepS
  • 65,107
  • 109
  • 251
  • 387

2 Answers2

4

You write to the Request stream and read from the Response stream.

    string postData = "name=t&description=tt";
    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
    // Set the ContentType property of the WebRequest.
    request.ContentType = "application/x-www-form-urlencoded";
    // Set the ContentLength property of the WebRequest.
    request.ContentLength = byteArray.Length;
    // Get the request stream.

    var stream = request.GetRequestStream();
    stream.Write( byteArray, 0, byteArray.Length );
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Thanks for that. However, can I not see the xml body of the request which is being sent out? – GurdeepS Mar 22 '11 at 00:05
  • @dotnetdev - maybe in the debugger. In any event, it's not XML, it's simply the string you specified, URL-encoded, so you already have the contents. – tvanfosson Mar 22 '11 at 00:09
  • @dotnetdev - if you absolutely had to you could derive your own request class from HttpWebRequest and override GetRequestStream so that it it returned the underlying stream wrapped with a filter. You could make the filter store the actual request written to the stream and make it available to you via some other property on your class. – tvanfosson Mar 22 '11 at 00:16
  • @dotnetdev: There's a very simple way to view network traffic in your .Net application: http://msdn.microsoft.com/en-us/library/ty48b824.aspx – Tergiver Mar 22 '11 at 01:50
0

The stream is not readable, because it's intended to be written to. See this link for a simple example:

http://www.netomatix.com/httppostdata.aspx

MusiGenesis
  • 74,184
  • 40
  • 190
  • 334