
Hey there! Ever wondered how your C# app can chat with a web server? That’s where HTTP requests swoop in to save the day. Whether you’re grabbing data from a REST API or sending stuff to a server, HTTP requests are your go-to tool. In this post, I’m diving into the best way to make C# HTTP requests using the mighty HttpClient class.
This article is updated for .NET 6 and Later. Reference to old code in case anyone is looking for. Cheers!
What Are HTTP Requests, Anyway?
First off, HTTP requests are how your app talks to the internet. Simple as that. You send a message—like “Hey, gimme some data!”—and the server replies. Back in the day, folks used clunky stuff like WebRequest, but that’s old news. Today, HttpClient is the king of C# HTTP requests. It’s fast, slick, and plays nice with async/await, which keeps your app snappy. Stick with me, and I’ll show you how to wield it like a pro.
FAQ: What’s the best way to make HTTP requests in C#?
Use HttpClient. It’s the modern, no-nonsense choice for rock-solid, asynchronous requests. We will explore both this and wrapper-library-based examples.
Setting Up Your C# Playground
Before we dive into the code, let’s set up shop. You’ll need .NET 6 or later—trust me, it’s worth it for the slick features and cross-platform goodness. Not sure what you’ve got? Open your terminal and type dotnet –version. If it’s below 6, head to dotnet.microsoft.com/download and snag the latest version. Done? Awesome.
Now, let’s whip up a new project. Fire up your terminal and run:
dotnet new console -n HttpRequestsDemo
cd HttpRequestsDemoCode language: JavaScript (javascript)Boom! You’ve got a shiny new console app ready to roll. Open it in your favorite editor (I’m a Visual Studio Code fan myself), and let’s start coding some C# HTTP requests.
Making Your First GET Request
Alright, let’s kick things off with a GET request. This is how you fetch data—like grabbing a blog post from a server. We’ll use a free API called JSONPlaceholder to test this out. It’s perfect for beginners and won’t bite. Here’s the code to get you started:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using var client = new HttpClient();
var response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
}Code language: JavaScript (javascript)Run that bad boy with dotnet run, and you’ll see some JSON magic flood your console. Cool, right? Let’s break it down:
- The HttpClient Line: I create one HttpClient instance here. This guy’s reusable—don’t keep making new ones, or you’ll clog up your app’s sockets. More on that later.
- The GetAsync Call: This sends a GET request to our URL. It’s async, so await keeps things smooth without freezing your app.
- Reading the Response: We grab the content as a string and print it. Easy peasy.
FAQ: How do I make a GET request in C#?
Use HttpClient.GetAsync With a URL, await the response, and read the content. Done.
Handling That Response Like a Boss
Okay, so you’ve got a response. Now what? Servers don’t always play nice, so you gotta check if things went smooth. Here’s how to handle it:
var response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine("Sweet! Here’s the data: " + content);
}
else
{
Console.WriteLine($"Oops, something’s off. Status: {response.StatusCode}");
}Code language: JavaScript (javascript)See that IsSuccessStatusCode check? It’s your best friend. If the status code is in the 200s (like 200 OK), you’re golden. Otherwise, you’ll know something’s up—like a 404 Not Found or a 500 Server Error. This keeps your app from choking on bad responses.
Sending Stuff with a POST Request
Now, let’s flip the script and send data with a POST request. Say you’re creating a new post on a server—this is how it’s done. Check this out:
var postData = new StringContent(
"{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}",
System.Text.Encoding.UTF8,
"application/json"
);
var response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", postData);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine("Post created! Here’s the response: " + content);
}
else
{
Console.WriteLine($"Dang it, failed with: {response.StatusCode}");
}Code language: JavaScript (javascript)Here’s the scoop:
- The StringContent Part: This is your data, formatted as JSON. We tell it to use UTF-8 encoding and set the content type to application/json so the server knows what’s up.
- The PostAsync Call: Sends that data to the server. Await it, and you’re good.
- Checking Success: Same deal as before—make sure it worked.
FAQ: How do I make a POST request in C#?
Use HttpClient.PostAsync With your data wrapped in StringContent. await The response and check if it’s successful.
Catching Errors Before They Wreck You
Real talk: stuff breaks. Servers crash, networks flake, and typos happen. You need to armor up with error handling. Here’s how I do it:
try
{
var response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts/1");
response.EnsureSuccessStatusCode(); // Throws if it’s not a success
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(content);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"HTTP meltdown: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Total chaos: {ex.Message}");
}Code language: JavaScript (javascript)That EnsureSuccessStatusCode method? It’s a beast—it’ll throw an exception if the status isn’t in the 200s, so you don’t miss a beat. Wrap it in a try-catch, and you’ll catch nasty surprises like network timeouts or bad URLs. Trust me, this saves headaches.
Best Practices to Follow:
Alright, you’re making C# HTTP requests like a champ. But let’s polish it up with some pro tips:
- Reuse HttpClient: Don’t create a new one every time—it’s a resource hog. One instance, used forever, is the way to go. In our console app, we did it right with using var client.
- ASP.NET Core Bonus: If you’re building a web app, use IHttpClientFactory. It’s a factory that churns out HttpClient instances, handling all the messy stuff like connection pooling. Look it up when you’re ready—it’s a game-changer.
- Set a Timeout: Add client.Timeout = TimeSpan.FromSeconds(30); to avoid hanging forever if the server’s napping.
These habits keep your app lean, mean, and ready for action.
RestSharp Library: The Fancy Alternative
Back in 2016, folks loved RestSharp, and it’s still kicking. It’s a slick wrapper around HttpClient that makes REST calls feel like a breeze. Here’s a taste:
using RestSharp;
var client = new RestClient("https://jsonplaceholder.typicode.com");
var request = new RestRequest("posts/1", Method.Get);
var response = await client.ExecuteAsync(request);
Console.WriteLine(response.Content);Code language: JavaScript (javascript)It’s shorter and sweeter, handling JSON and stuff for you. But honestly? HttpClient does the job fine without extra baggage. Your call—stick with the built-in power or grab RestSharp for some flair.
Wrapping It Up
There you have it, folks! You’ve mastered C# HTTP requests with HttpClient. We’ve tackled GET and POST requests, tamed errors, and sprinkled in some best practices. You’re ready to hit the ground running. Go mess around with APIs—try fetching weather data or posting tweets (well, fake ones on JSONPlaceholder). The world’s your oyster now.
Got questions? Drop ‘em below. Happy 👀 #️⃣ coding!
Discover more from CodeSamplez.com
Subscribe to get the latest posts sent to your email.

I am trying to make call to pages in facebook Graph API and retrive in my application. Do you suggest me to go through install Facebook C# SDK or to use the code above for accessing.
Kind regards,
Naim
Depends on the spec domain. If you are creating an fully Facebook based application, then I will suggest you to use the facebooksdk. For simple usage(and to understand better how they works), you can go with the manual approaches that i have discussed in few posts. Hope this helps.
i need how to connect with user and server
Hi Rana,
Thanks for you post.
I had a error at line 57 dataStream = request.GetRequestStream();
The error msg is “Cannot send a content-body with this verb-type”
Is there any extra I need to do?
Thanks
Warm Regards
Phil
enter the method name as “POST”
GET method does not work.
The error msg is “Cannot send a content-body with this verb-type”
what if I want to call a javascript function on a page?
like:
httpget(uri, “javascript:ChangeAcc()”);
happy programming 🙂
Modification for GET request working
public MyWebRequest(string url, string method, string data)
: this(url, method)
{
if (request.Method == “POST”)
{
// Create POST data and convert it to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(data);
// Set the ContentType property of the WebRequest.
request.ContentType = “application/x-www-form-urlencoded”;
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
else
{
String finalUrl = string.Format(“{0}{1}”, url, “?” + data);
request = WebRequest.Create(finalUrl);
WebResponse response = request.GetResponse();
//Now, we read the response (the string), and output it.
dataStream = response.GetResponseStream();
}
}
thank you
Dear Sir,
I have 2 doubts
1. I am not getting should I use same url or replace it to my domain url which I dont have.
http://www.yourdomain.com
2.
Getting error at below line
public string GetResponse()
{
// Get the original response.
WebResponse response = request.GetResponse();
Error is
WebException was unhandled by user code
“The remote server returned an error: (405) Method Not Allowed.”
Kindly help me to resolve it.
How would you implement it using a username and password?
how do i close the connections immediately? i am getting the 4 instances ….
it is not necessary to close a stream when you’ve already called Close() on its assigned StreamWriter/Reader. it does it for you automatically.
it’s also a good practice to use the “using” keyword when working with streams.
for instance if we have a stream ‘s’ and string ‘stuff’
using (StreamWriter sw = new StreamWriter (s) )
{
sw.Write (stuff);
}
once the end of the block is reached, the StreamWriter object gets disposed, calling Close() on itself before that happens and in turn closing the underlying stream as well.
I’m using the following convenience methods to write to and read from streams when working with http requests, feel free to use them yourself.
public static void StringToStream(Stream stream, string content)
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(content);
}
}
public static string StringFromStream(Stream stream)
{
string content;
using (StreamReader reader = new StreamReader(stream))
{
content = reader.ReadToEnd();
}
return content;
}
How do i post and retrieve data to/fro a remote MS SQL using the this http webserver
Hello. I’m getting:
Cannon implicitly convert type ‘MyWebRequest’ to ‘System.Net.WebRequest’, On WebRequest myRequest = new MyWebRequest(“http://www.minecraft.net”,”POST”,”a=value1&b=value2″);
It would be very helpful to see what ‘using’ statements you would need in both the example code and the class that you created.
I find so many examples were people give code but do not give the using statements to know which areas of the .net library to call. This would be extremely helpful for people are are just starting out and don’t have common library’s or using statements memorized.
Thank you
Can you please elaborate how to run this program in vs
Also is it necessary to install IIS to run this program?
You can run it on either a desktop application or on web application. This will facilitate you in cases, where your application itself need to request to other external web http get or post request and process the response. You don’t need to install iis.
Hi, im need get one request of another website, they send to me via POST, but i dont know how i get in my page, they send 2 parameters:
Like that: notificationCode=766B9C-AD4B044B04DA-77742F5FA653-E1AB24
notificationType=transaction
Im using C#
What i go put on pageload to get this parameters?
Thanks for all help.
Hi, you can handle them is the same way you handle your own site’s GET/POST request. Just need to grab the ‘Request.Params[“SomeID”]’ or Request.Querystring(“parameter1”) in your c# code, depending what type of http request they are sending to your application. Hope this helps.
Hello When i am using this code then i am getting NULL value in return when i am accessing my PHP file directly from Browser.
and even in OUTPUT window of VS, it display just the value of a only that is “Value1” nothing else.
my client side application is in C# using help from your code
and my Service Side application is in PHP and the statement i am using in my PHP file is
and one more consultation, i would like to post data that the client will enter in Textbox and i tried to put that in query but failed.
So, it would be really appreciable if you can help me for that also along with the NULL value Return
Thanks for your code. It’s very useful
Thanks Ali, very useful
Very Useful! What a pain in the ass the default WebRequest with POST parameters…
Thank you very much!
Nice article. As per my research on this topic, I have seen that we can improve the security concerns regarding GET request by using HTTPS protocol.
I want to get response from this url:
https://testapi.internet.bs/Domain/Check?Domain=HASANUDDIN.INFO&ApiKey=testapi&Password=testpass”
Note: this the original web http://www.internetbs.net/ResellerRegistrarDomainNameAPI/api/01_domain_related/01_domain_check
but i got this error message:
“The operation has timed out”
Could you tell me is there something wrong from my code, here is my code:
//create the constructor with post type and few data
MyWebRequest myRequest = new MyWebRequest(“https://testapi.internet.bs/Domain/Check”, “POST”, “Domain=HASANUDDIN.INFO&ApiKey=testapi&Password=testpass”);
//show the response string on the console screen.
Console.WriteLine(myRequest.GetResponse());
as far I can track, you need to provide “GET” instead of “POST”(as all variables in url are passed in GET method). May be the server only accepts GET requests.
thx, your code is very usefull, but how to make this webrequest class asyncronously ?
Good post to get the initial structure, but as mentioned in previous comments, this only works if a response of 200 is received, but errors out on other responses. This is not hard to add, but just don’t implement into a solution without adding necessary additional code.
thanks you so much!..
Hi,
How could you use this to replace this Curl statement
curl -H “X-Auth-User: bryanoliver” -H “X-Auth-Expires: 1406485297” -H “X-Auth-Key: 946ddd08f5fbcb3ddb0c91e3785f0630” “-H” “Accept: application/xml” “https://acb7b192c688.cloud.elementaltechnologies.com/api/jobs/1”
{“The remote server returned an error: (500) Internal Server Error.”}
Dear Ali Ahsan,
How can I use this in a multiple call?
To give you the idea. I created a 2 method that calls different data.
For instance:
checkExisting_data() – for getting hours list
addComboList() – for getting projects list
But when I put this both on the Form Load, only one method is working and the other is not but when I commented the first one the second method works. So i guess there is nothing wrong with my method
//Sample Code
http://pastebin.com/bzWczKXc
Please advise!
Thank you in advance
This script does not RUN.. any ideas. also i want to know how i can get the URL connect to display TRUE as in connection is TRUE .
That way i know the code works and POST.
THis is what i have but it does not work.
I want to POST to URL with the STRING like:
http://www.myurl.com/bin/usernamehere.passwordhere.morestuffhere.timeanddatehere.
can anyone help.?
Code:
http://pastebin.com/Dnx7Dpam
Great class man! really simple and got it working in a second! Thanks for your efforts!
what are the changes we need to do if we want to use it for a Windows Phone App
i want to send an http request.. but i want that page of this http request is not show to the user….
please solve my problem
I need to send a request to a payment switch with the following parameters in asp.net C# and receive an json response, any idea how
Sample Request (JSON)
GET
stageserv.interswitchng.com/test_paydirect/api/v1/gettransaction.json?productid=21&transactionreference=8421941122&amount=300000 HTTP/1.1
UserAgent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.239)
Hash: F6FF2E22F99D93DDDA52D71811FD92B3A71FA1968A66216E0D310DAD
Sample Response (JSON)
HTTP/1.0 200 OK
Date: Tue, 30 Oct 2012 16:12:17 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 333
{“Amount”:300000,”CardNumber”:”6055″,”MerchantReference”:”8421941122″,”PaymentReference”:”ZIB|WEB|VNA|15-10-2012|015933″, “RetrievalReferenceNumber”:”000000538268″, “LeadBankCbnCode”:null, “LeadBankName”:null, “SplitAccounts[],”TransactionDate”:”2012-10-15T11:07:54.547″,”ResponseCode”:”00″,”ResponseDescription”:”Approved Successful”}
Please help
Thank you for the information and explanation.
Do you know how to “upload a file” using a POST request?
Thanks Ali for your Work !
can i use async for same method ??
Super simple, and complete! Sometimes it’s difficult to remember which order C# objects need to be created to get a good response. Your article was very helpful in reminding me how to properly get content into the right part of the response / request objects in C#. Thanks!
Dear Sir,
How to use this wrapper class in my webpage .
i have returmUrl.Aspx and .Cs page.
please tell me the procedure for use of this wrapper class for handling HTTP get/Post request from payment gatway.
How it will usefull for pickup response from payment gayway.
waiting hopefully.
thank in advance.
Hi,
Below is my code and they are pretty simple. However, I’m encountering (500) Internal Server Error from this line.
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
public void GetRequestID(string atoken)
{
string webpage_data = “INC000003785314”;
string webpage = “https://arstest.micron.com:9443/api/arsys/v1/entry/HPD%3AIncidentInterface/?fields=values(Request ID)&q=’Incident Number’%3D”;
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] data = encoding.GetBytes(webpage_data);
webpage = webpage + webpage_data;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(webpage);
myRequest.Credentials = CredentialCache.DefaultCredentials;
myRequest.Method = “GET”;
myRequest.ContentType = “application/json”;
myRequest.Headers.Add(“Authorization”, atoken);
HttpWebResponse response = (HttpWebResponse)myRequest.GetResponse();
Stream receive_stream = response.GetResponseStream();
StreamReader read_stream = new StreamReader(receive_stream, Encoding.UTF8);
string str = read_stream.ReadToEnd();
response.Close();
read_stream.Close();
}
POST using
1) XML
How get response in XML
and
2) JSON
How get response in JSON
real world sampes?
Thank you very much.