Create HTTP post request and receive response using C# console application
Take a look at the System.Net.WebClient
class, it can be used to issue requests and handle their responses, as well as to download files:
http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx
C# POST request to webapi using a console program
You are probably getting an error because the final address is your baseAddress + post address, that is: http://localhost:8443/nrcApi/nrcApi , which doesn't exist
Try changing your client.BaseAddress to:
client.BaseAddress = new Uri("https://localhost:8443/");
For SSL connection errors, try generating a trusted certificate:
Make https call using httpclient
C# Console Application to Respond to HTTP POST requests
You don't need to use sockets - .NET has had an HTTP/1.1 server since v2.0.
See: MSDN: HttpListener
API POST call from Console Application
This is working for me.
public async Task CallWebAPIAsync()
{
var student = "{'Id':'1','Name':'Steve'}";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:58847/");
var response = await client.PostAsync("api/values", new StringContent(student, Encoding.UTF8, "application/json"));
if (response != null)
{
Console.WriteLine(response.ToString());
}
}
Send HTTP POST request in .NET
There are several ways to perform HTTP GET and POST requests:
Method A: HttpClient (Preferred)
Available in: .NET Framework 4.5+, .NET Standard 1.1+, and .NET Core 1.0+.
It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.
using System.Net.Http;
Setup
It is recommended to instantiate one HttpClient
for your application's lifetime and share it unless you have a specific reason not to.
private static readonly HttpClient client = new HttpClient();
See HttpClientFactory
for a dependency injection solution.
POST
var values = new Dictionary<string, string>
{
{ "thing1", "hello" },
{ "thing2", "world" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("http://www.example.com/recepticle.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();GET
var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");
Method B: Third-Party Libraries
RestSharp
POST
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}");
request.AddParameter("thing1", "Hello");
request.AddParameter("thing2", "world");
request.AddHeader("header", "value");
request.AddFile("file", path);
var response = client.Post(request);
var content = response.Content; // Raw content as string
var response2 = client.Post<Person>(request);
var name = response2.Data.Name;
Flurl.Http
It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is available via NuGet.
using Flurl.Http;
POST
var responseString = await "http://www.example.com/recepticle.aspx"
.PostUrlEncodedAsync(new { thing1 = "hello", thing2 = "world" })
.ReceiveString();GET
var responseString = await "http://www.example.com/recepticle.aspx"
.GetStringAsync();
Method C: HttpWebRequest (not recommended for new work)
Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps HttpClient
, is less performant, and won't get new features.
using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader
POST
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var postData = "thing1=" + Uri.EscapeDataString("hello");
postData += "&thing2=" + Uri.EscapeDataString("world");
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();GET
var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Method D: WebClient (Not recommended for new work)
This is a wrapper around HttpWebRequest
. Compare with HttpClient
.
Available in: .NET Framework 1.1+, NET Standard 2.0+, and .NET Core 2.0+.
In some circumstances (.NET Framework 4.5-4.8), if you need to do a HTTP request synchronously, WebClient
can still be used.
using System.Net;
using System.Collections.Specialized;
POST
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
var response = client.UploadValues("http://www.example.com/recepticle.aspx", values);
var responseString = Encoding.Default.GetString(response);
}GET
using (var client = new WebClient())
{
var responseString = client.DownloadString("http://www.example.com/recepticle.aspx");
}
HTTP Post from Console application C#
This article on MSDN describe how to post data using HttpWebRequest. Set property HttpWebRequest.AllowAutoRedirect false and process GetResponse and GetResponseStream
Related Topics
Why Gettype Returns System.Int32 Instead of Nullable<Int32>
How to Determine the True Pixel Size of My Monitor in .Net
How to Configure Many to Many Relationship Using Entity Framework Fluent API
Selecting the Size of a System.Drawing.Icon
How to Terminate a Thread in C#
Process.Start to Open an Url, Getting an Exception
Client Id for Property (ASP.NET MVC)
No Access to the Session Information Through Signalr Hub. Is My Design Is Wrong
How to Disable Visual Styles for Just One Control, and Not Its Children
Using Graphics.Drawimage() to Draw Image with Transparency/Alpha Channel
C#: How to Add Subitems in Listview
How to Get a Unique Identifier for a Device Within Windows 10 Universal
Cannot Deserialize the Current JSON Array (E.G. [1,2,3])
The Type Initializer for 'Emgu.Cv.Cvinvoke' Threw an Exception