142

I'm creating a web request in ASP.NET and I need to add a bunch of data to the body. How do I do that?

var request = HttpWebRequest.Create(targetURL);
request.Method = "PUT";
response = (HttpWebResponse)request.GetResponse();
abatishchev
  • 98,240
  • 88
  • 296
  • 433
William Calleja
  • 4,055
  • 11
  • 41
  • 51

3 Answers3

120

With HttpWebRequest.GetRequestStream

Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

From one of my own code:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}
Torbjörn Hansson
  • 18,354
  • 5
  • 33
  • 42
  • Hi Torbjorn, I'm using the request so I can get the 'request.GetResponse();', in the above example how would that work? – William Calleja Nov 23 '10 at 12:55
  • 1
    When you call GetRequestStream() it makes the call to the server. So, you would have to add that to the end of the above example. – Torbjörn Hansson Nov 23 '10 at 13:04
  • 1
    Is there a way to see the full text inside a request object for debugging purposes? I tried serializing it and tried using a StreamReader, but no matter what I do I can not see the data I just wrote to the request. – James Nov 17 '16 at 19:36
  • Fan-freaking-tastic! –  Apr 11 '17 at 15:37
  • @James, You should be able to use fiddler or wireshark to see the full request with it's body. – RayLoveless Jan 29 '18 at 21:03
52

Update

See my other SO answer.


Original

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • Are you missing something? Like an httpWReq.Content = newStream; you are not using your newStream object with your webRequest. – Yogurtu Mar 02 '15 at 15:39
  • 4
    To answer @Yogurtu's question for completeness, the `Stream` object that `newStream` points to writes directly to the body of the request. It is accessed by the call to `HttpWReq.GetRequestStream()`. There is no need to set anything else on the request. – MojoFilter Aug 18 '15 at 18:57
9

The answers in this topic are all great. However i'd like to propose another one. Most likely you have been given an api and want that into your c# project. Using Postman, you can setup and test the api call there and once it runs properly, you can simply click 'Code' and the request that you have been working on, is written to a c# snippet. like this:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "development+XXXXXXXX-admin@XXXXXXX.XXXX");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

The code above depends on the nuget package RestSharp, which you can easily install.

real_yggdrasil
  • 1,213
  • 4
  • 14
  • 27