C# HTTP Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
To send an HTTP POST web request to a URL in C#, you can use the HttpClient
class along with the PostAsync
method. Here is an example:
using System.Net.Http; using System.Threading.Tasks; // ... public async Task<string> PostRequest(string url, string data) { using (var client = new HttpClient()) { var content = new StringContent(data, Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, content); return await response.Content.ReadAsStringAsync(); } }
In this example, we use the StringContent
class to create the HTTP request body with the data
parameter. We also set the content type to application/json
using the MediaTypeHeaderValue
class. Finally, we call the PostAsync
method of the HttpClient
instance with the URL and content.
To send an asynchronous HTTP POST web request to a URL in C#, you can use the PostAsync
method with the await
keyword to make the call asynchronously. Here is an example:
using System.Net.Http; using System.Threading.Tasks; // ... public async Task<string> PostRequestAsync(string url, string data) { using (var client = new HttpClient()) { var content = new StringContent(data, Encoding.UTF8, "application/json"); var response = await client.PostAsync(url, content); return await response.Content.ReadAsStringAsync(); } }
In this example, we use the async
and await
keywords to make the PostAsync
method call asynchronous. The rest of the code is similar to the previous example.
C# HttpClient POST example:
HttpClient
.using (HttpClient client = new HttpClient()) { var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
C# HTTPClient send POST request:
HttpClient
.HttpClient client = new HttpClient(); var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content);
POST request in C# using WebClient:
WebClient
.using (WebClient client = new WebClient()) { var data = new NameValueCollection { { "key1", "value1" }, { "key2", "value2" } }; byte[] result = client.UploadValues("https://api.example.com/post", "POST", data); // Process result }
Asynchronous HTTP POST request in C#:
using (HttpClient client = new HttpClient()) { var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
Sending JSON in POST request C#:
using (HttpClient client = new HttpClient()) { var data = new { key1 = "value1", key2 = "value2" }; var json = JsonConvert.SerializeObject(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
C# HTTPClient POST request with form data:
HttpClient
.using (HttpClient client = new HttpClient()) { var formData = new MultipartFormDataContent { { new StringContent("value1"), "key1" }, { new StringContent("value2"), "key2" } }; HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", formData); // Process response }
REST API POST request in C#:
using (HttpClient client = new HttpClient()) { var data = new { key1 = "value1", key2 = "value2" }; var json = JsonConvert.SerializeObject(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/api/resource", content); // Process response }
Deserialize JSON from POST request in C#:
using (HttpClient client = new HttpClient()) { var data = new { key1 = "value1", key2 = "value2" }; var json = JsonConvert.SerializeObject(data); var content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); if (response.IsSuccessStatusCode) { string jsonResponse = await response.Content.ReadAsStringAsync(); var result = JsonConvert.DeserializeObject<MyModel>(jsonResponse); // Process result } }
HTTP POST request with headers in C#:
using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization", "Bearer your_access_token"); var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
C# HTTP POST request timeout:
using (HttpClient client = new HttpClient()) { client.Timeout = TimeSpan.FromSeconds(10); // Set timeout to 10 seconds var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
Handling redirects in C# HTTP POST request:
using (HttpClientHandler handler = new HttpClientHandler()) using (HttpClient client = new HttpClient(handler)) { handler.AllowAutoRedirect = true; var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
C# HTTP POST request with authentication:
using (HttpClient client = new HttpClient()) { var credentials = new NetworkCredential("username", "password"); client.DefaultRequestHeaders.Authorization = new CredentialCache { { new Uri("https://api.example.com"), "Basic", credentials } }; var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
URL encoding in C# HTTP POST request:
string parameterValue = "value with spaces"; string encodedValue = Uri.EscapeDataString(parameterValue); var content = new StringContent($"key={encodedValue}", Encoding.UTF8, "application/x-www-form-urlencoded");
C# POST request with query string:
using (HttpClient client = new HttpClient()) { var parameters = new Dictionary<string, string> { { "param1", "value1" }, { "param2", "value2" } }; var content = new FormUrlEncodedContent(parameters); HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); // Process response }
C# HTTP POST request error handling:
using (HttpClient client = new HttpClient()) { var content = new StringContent("Hello, World!", Encoding.UTF8, "text/plain"); try { HttpResponseMessage response = await client.PostAsync("https://api.example.com/post", content); response.EnsureSuccessStatusCode(); // Throws exception for non-success status codes // Process response } catch (HttpRequestException ex) { // Handle exception } }
Send file in HTTP POST request C#:
using (HttpClient client = new HttpClient()) using (var fileStream = File.OpenRead("path/to/file.txt")) { var content = new MultipartFormDataContent(); content.Add(new StreamContent(fileStream), "file", "file.txt"); HttpResponseMessage response = await client.PostAsync("https://api.example.com/upload", content); // Process response }