Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
Curyous Avatar asked Apr 03 '11 03:04

Curyous


People also ask

What is the difference between Httpclient and HttpWebRequest?

WebClient is just a wrapper around HttpWebRequest, so it uses HttpWebRequest internally. The WebClient bit slow compared to HttpWebRequest. But is very much less code. we can use WebClient for simple ways to connect and work with HTTP services.

How do I dispose of HttpWebRequest?

HttpWebRequest does not implement IDisposable so it does not require disposing. just set the httprequest object to null once your done with it.

What is HttpWebRequest C#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.

Is HttpWebRequest deprecated?

NET 6, the WebRequest, WebClient, and ServicePoint classes are deprecated. The classes are still available, but they're not recommended for new development. To reduce the number of analyzer warnings, only construction methods are decorated with the ObsoleteAttribute attribute.


2 Answers

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(); 
like image 51
Simon Fox Avatar answered Sep 28 '22 10:09

Simon Fox


.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;     } } 
like image 40
Joshcodes Avatar answered Sep 28 '22 08:09

Joshcodes