An HttpWebRequest has the properties ContentLength and ContentType, but how do you actually set the content of the request?
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.
HttpWebRequest does not implement IDisposable so it does not require disposing. just set the httprequest object to null once your done with it.
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.
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.
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();
.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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With