Curyous
Curyous

Reputation: 8866

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

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

Upvotes: 40

Views: 65913

Answers (5)

Justin
Justin

Reputation: 424

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);

Upvotes: 8

Joshcodes
Joshcodes

Reputation: 8871

.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;
    }
}

Upvotes: 8

Simon Fox
Simon Fox

Reputation: 10561

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();

Upvotes: 44

smartcaveman
smartcaveman

Reputation: 42246

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();

Upvotes: 1

stephbu
stephbu

Reputation: 5082

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.

Upvotes: 5

Related Questions