How to POST and GET url with parameters in C#?

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);


1 yıl önce eklendi

- How to POST and GET url with parameters in C#?
- Open a text file and read line by line in C#
- Convert.ToInt32() vs Int32.Parse() in C#
- How to C# Linq Group By by paramater/field names
- Simple Injector
- How to check memory consumption in c#
- How can I implement C/C++ "union" in C#?
- How to Open and Read From Excel File in C#
- Weak References
- Lazy Initialization
- Enable Nuget Package Restore
- OnixS FIX Engine
- Rapid Addition FIX API
- How to change DateTime format in C#
- How to change number decimal seperator in C#?
2
1