C# – Several Ways To Perform Http GET and POST Requests

Legacy

using System.Net;

POST

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
 postData += "&thing2=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();

WebClient (Also now legacy)

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

HttpClient

using System.Net.Http;

POST

using (var client = new HttpClient())
{
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

using (var client = new HttpClient())
{
var responseString = client.GetStringAsync("http://www.example.com/recepticle.aspx");
}

RestSharp

Tried and tested library for interacting with REST APIs. Portable. Available via NuGet.

Flurl.Http

Newer library sporting a fluent API and testing helpers. HttpClient under the hood. Portable. 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();

Source

3 thoughts on “C# – Several Ways To Perform Http GET and POST Requests

  1. Hello,
    I’m looking for a solution to post data via api. Your code look easy. But i have always an issue to post data with 2 headers. I’m blocked since 4 days. Can you help me please. I ‘ve tried with webclient and httpClient but nothing.

    Thanks in advance
    Asma

Leave a comment