0

I recently learned how to make get HTTP requests with C#'s System.Net.Http library. I'm wondering how I'd go about making a post request using headers. Is there any simple way to do so? I haven't really tried much. But in python here's how I'd do it:

import requests
authorization_variable = "something here"
headers = {            'Authorization': authorization_variable, 'Content-Type': 'application/json','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'};
r = requests.post("https://example.com/", headers=headers)

That's basically what I want to achieve but in C#

The post request I'm looking to do takes 3 headers:

authorization,

Content-Type,

User-Agent.

My current code:

static async Task httpfunc()
        {
            var client = new HttpClient();
            var responseString = await client.GetStringAsync("https://pastebin.com/raw/sUJb5t2Q");
            Console.WriteLine(Convert.ToString(responseString));
            Console.ReadLine();
}
XenixSX
  • 1
  • 6
  • 1
    Please post the working c# code you have so far. – Igor Apr 20 '21 at 17:59
  • Edited! Please refresh the page – XenixSX Apr 20 '21 at 18:01
  • 2
    There are tons of examples on how to use `HttpClient`. You are telling me you found nothing anywhere? – Andy Apr 20 '21 at 18:02
  • 1
    Thanks. Check out the [`SendAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.sendasync?view=net-5.0) method which gives you much finer grained control over what is sent using the `HttpRequestMessage`. – Igor Apr 20 '21 at 18:02
  • 1
    ... or [PostAsync](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.postasync?view=net-5.0) which also allows to send Headers in its [HttpContent](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent?view=net-5.0). – Filburt Apr 20 '21 at 18:06

0 Answers0