How to set the content of an HttpWebRequest in C#?

Curyous picture Curyous · Apr 3, 2011 · Viewed 54.8k times · Source

An HttpWebRequest has the properties ContentLength and ContentType, but how do you actually set the content of the request?

Answer

Simon Fox picture Simon Fox · Apr 3, 2011

The following should get you started

byte[]  buffer = ...request data as bytes
var webReq = (HttpWebRequest) WebRequest.Create("http://127.0.0.1/target");

webReq.Method = "REQUIRED METHOD";
webReq.ContentType = "REQUIRED CONTENT TYPE";
webReq.ContentLength = buffer.Length;

var reqStream = webReq.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

var webResp = (HttpWebResponse) webReq.GetResponse();