40

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

Curyous
  • 8,716
  • 15
  • 58
  • 83

5 Answers5

44

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();
Simon Fox
  • 10,409
  • 7
  • 60
  • 81
  • 4
    Though it may be obvious to some, make sure to set the Content Type BEFORE writing to the request stream. – bsayegh Feb 26 '14 at 20:13
8

.NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) provides a lot of additional flexibility in setting the request content. Here is an example:

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}
Joshcodes
  • 8,513
  • 5
  • 40
  • 47
  • Hi, do you have an example on how to call this function? should I create the Web request ( request) first , set the content type (request.ContentType = "application/x-www-form-urlencoded"), method = Post, content length, then do a Stream (e.g. Stream dataStream = WebRequest.GetRequestStream();) And after that pass it to the parameter paramFileStream ? like this? Stream uploadstream = Upload(actionUrl, paramString, dataStream, byteArray); ? – Alexei May 10 '17 at 12:51
7

Here's a different option for posting info without messing with Bytes and Streams. I personally find it easier to follow, read, and debug.

// Convert Object to JSON
var requestMessage = JsonConvert.SerializeObject(requestObject);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");

// Create the Client
var client = new HttpClient();
client.DefaultRequestHeaders.Add(AuthKey, AuthValue);

// Post the JSON
var responseMessage = client.PostAsync(requestEndPoint, content).Result;
var stringResult = responseMessage.Content.ReadAsStringAsync().Result;

// Convert JSON back to the Object
var responseObject = JsonConvert.DeserializeObject<ResponseObject>(stringResult);
Justin
  • 414
  • 4
  • 8
5

HttpWebRequest's RequestStream is where the action is at - rough code...

//build the request object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://someapi.com/);
//write the input data (aka post) to a byte array
byte[] requestBytes = new ASCIIEncoding().GetBytes(inputData);
//get the request stream to write the post to
Stream requestStream = request.GetRequestStream();
//write the post to the request stream
requestStream.Write(requestBytes, 0, requestBytes.Length);

If you're sending extended chars, use UTF8Encoding, make sure you set the right content-type/charset header too.

stephbu
  • 5,072
  • 26
  • 42
  • need to set the method on the request as well - and usually also the contenttype – Robert Levy Apr 03 '11 at 04:27
  • yeah sure Robert - I left out *a lot of code* like actually sending the request too :) It's good for the OP and brevity to complete the dots. I marked it as a community answer if you want to make it more complete. – stephbu Apr 04 '11 at 07:33
1

HttpWebRequest.GetRequestStream() gets the request Stream. After you have set the headers, use GetRequestStream() and write the content to the stream.

This post explains how to transmit files using HttpWebRequest, which should provide a good example of how to send content.

But, basically the format would be

 var stream = request.GetRequestStream();
 stream.Write( stuff );
 stream.Close();
 var response = request.GetResponse();
Community
  • 1
  • 1
smartcaveman
  • 41,281
  • 29
  • 127
  • 212