40

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

1

5 Answers 5

45

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Though it may be obvious to some, make sure to set the Content Type BEFORE writing to the request stream.
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; } } 

1 Comment

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

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

2 Comments

Where is StringContent from?
Oh you are using Microsoft.Net.Http, which is new and a better answer.
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.

2 Comments

need to set the method on the request as well - and usually also the contenttype
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.
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(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.