How to POST and GET url with parameters in C#?
REST API (RESTful API, REpresentational State Transfer) is one of the most frequently used technologies in communicating between websites, APIs (Application Programming Interface) and services.
4 different commands are used when transferring data with the REST API: GET, POST, PUT, DELETE. In most cases, the function of the PUT and DELETE commands are performed by the other two commands.
When making a request with the GET command, all the attached parameters are written in the address section. It is not suitable for sending to many parameters or large data.
Whereas, when making a request with the POST command, parameters are added as attachments to the request package. When the number of parameters increases or when sending files, you should prefer the POST method.
There are several ways to perform GET and POST operations in C#. This page will exemplify how these operations can be performed using the HttpClient method.
Single function to POST and GET with parameters
public static async Task<String> CallApi(String
uri,
Dictionary<string, string> parameters = null, Boolean isPost = true)
{
using (HttpClient client = new HttpClient())
{
var content = new FormUrlEncodedContent(parameters);
if (isPost)
{
var response = await client.PostAsync(uri, content);
return await response.Content.ReadAsStringAsync();
}
if (parameters != null && parameters.Count > 0)
uri = uri + "?" + content.ReadAsStringAsync().Result;
return await client.GetStringAsync(uri);
}
}
var parameters = new Dictionary<string, string>()
{ { "username", "How" }, { "password", "C#" } };
var result = CallApi("http://www.howcsharp.com", parameters, false);
Console.WriteLine(result.Result);