Send Http Post Request in .Net

Send HTTP POST request in .NET

There are several ways to perform HTTP GET and POST requests:



Method A: HttpClient (Preferred)

Available in: .NET Framework 4.5+, .NET Standard 1.1+, and .NET Core 1.0+.

It is currently the preferred approach, and is asynchronous and high performance. Use the built-in version in most cases, but for very old platforms there is a NuGet package.

using System.Net.Http;

Setup

It is recommended to instantiate one HttpClient for your application's lifetime and share it unless you have a specific reason not to.

private static readonly HttpClient client = new HttpClient();

See HttpClientFactory for a dependency injection solution.



  • POST

      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

      var responseString = await client.GetStringAsync("http://www.example.com/recepticle.aspx");


Method B: Third-Party Libraries

RestSharp

  • POST

       var client = new RestClient("http://example.com");
    // client.Authenticator = new HttpBasicAuthenticator(username, password);
    var request = new RestRequest("resource/{id}");
    request.AddParameter("thing1", "Hello");
    request.AddParameter("thing2", "world");
    request.AddHeader("header", "value");
    request.AddFile("file", path);
    var response = client.Post(request);
    var content = response.Content; // Raw content as string
    var response2 = client.Post<Person>(request);
    var name = response2.Data.Name;

Flurl.Http

It is a newer library sporting a fluent API, testing helpers, uses HttpClient under the hood, and is portable. It is 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();


Method C: HttpWebRequest (not recommended for new work)

Available in: .NET Framework 1.1+, .NET Standard 2.0+, .NET Core 1.0+. In .NET Core, it is mostly for compatibility -- it wraps HttpClient, is less performant, and won't get new features.

using System.Net;
using System.Text; // For class Encoding
using System.IO; // For StreamReader


  • POST

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

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


Method D: WebClient (Not recommended for new work)

This is a wrapper around HttpWebRequest. Compare with HttpClient.

Available in: .NET Framework 1.1+, NET Standard 2.0+, and .NET Core 2.0+.

In some circumstances (.NET Framework 4.5-4.8), if you need to do a HTTP request synchronously, WebClient can still be used.

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

Sending a POST request to a URL from C#

You have to create a request stream and write to it, this link here has several ways to do this either with HttpWebRequest, HttpClient or using 3rd party libraries:

Posting data using C#

How to send a post request in dotnet with a list of request headers

Your code isn't far off, here's an example that I had in one of my projects ...

using (var httpClient = new HttpClient())
{
var requestString = "{\"authCode\": \"0000000001Nk1EEhZ3pZ73z700271891\" }";

// Setup the HttpClient and make the call and get the relevant data.
httpClient.BaseAddress = new Uri("https://bounties-backend-mini-program.herokuapp.com");

httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

var request = new HttpRequestMessage(HttpMethod.Post, $"/api/userInfo");
request.Content = new StringContent(requestString, System.Text.Encoding.UTF8, "application/json");

var response = await httpClient.SendAsync(request);
var responseContent = await response.Content.ReadAsStringAsync();

Console.WriteLine(JsonConvert.SerializeObject(response.Headers.ToList()));

if (response.IsSuccessStatusCode)
{
Console.WriteLine("Successful");
Console.WriteLine(responseContent);
}
else
{
Console.WriteLine("Not successful");
}
}

... obviously, it has varying degrees of thought for the scenario at hand but just adapt it as need be.

POST Request using .Net Core 3.1 and HTTP Request of Power Automate

Try converting your Person model to JSON and just use simple PostAsync

Person person = new Person
{
Name = "Juan Dela Cruz",
Age = 32
};
var personJSON = JsonConvert.SerializeObject(person);
var buffer = System.Text.Encoding.UTF8.GetBytes(personJSON);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var response = await client.PostAsync(SD.ApiUri, byteContent);

Send HTTP Post with .Net Core

using

using System.Net.Http;

and your code will be

var url = "http://yoursite.com/Home/Insert";
var data = new {"recipient"= "stefan.", "body"="Test"};

using(var client = new HttpClient())
{
var response = await client.PostAsJsonAsync(url, data);
string responseContent = await response.Content.ReadAsStringAsync(); // only to see response as text ( debug perpose )

var result = await ProcessedResult<TResult>(response); // cast it to TResult or any type that you expect to retrieve

}

How to send HTTP post request to another API in c#?

You can try this:

//Yours entity.
MyEntity myEntity;
HttpResponseMessage response;
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("https://yourApiAdress.com");
//Yours string value.
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("MyStringContent", "someString")
});
//Sending http post request.
response = await httpClient.PostAsync($"rest/of/apiadress/", content);
}

//Here you save your response to Entity:

var contentStream = await response.Content.ReadAsStreamAsync();
//Options to mach yours naming styles.
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = SnakeCaseNamingPolicy.Instance
};
//Here you go. Yours response as an entity:
myEntity = await JsonSerializer.DeserializeAsync<MyEntity>(contentStream, options);

Snake case naming policy:

using Newtonsoft.Json.Serialization; //For SnakeCaseNamingPolicy.

public class SnakeCaseNamingPolicy : JsonNamingPolicy
{
private readonly SnakeCaseNamingStrategy _newtonsoftSnakeCaseNamingStrategy
= new SnakeCaseNamingStrategy();

public static SnakeCaseNamingPolicy Instance { get; } = new SnakeCaseNamingPolicy();

public override string ConvertName(string name)
{
return _newtonsoftSnakeCaseNamingStrategy.GetPropertyName(name, false);
}
}

If yours another API JSON response looks like:

{
"some_object" : "someValue",
}

Then your entity should look like:

public class MyEntity
{
public object SomeObject { get; set;}
}

Send JSON data in http post request C#

try this

using (var client = new HttpClient())
{
var contentType = new MediaTypeWithQualityHeaderValue("application/json");
var baseAddress = "https://....";
var api = "/controller/action";
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(contentType);

var data = new Dictionary<string,string>
{
{"id","72832"},
{"name","John"}
};

var jsonData = JsonConvert.SerializeObject(data);
var contentData = new StringContent(jsonData, Encoding.UTF8, "application/json");

var response = await client.PostAsync(api, contentData);

if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<object>(stringData);
}
}

Update

If the request comes back with Json data in the form `

 { "return":"8.00", "name":"John" }

you have to create result model

public class ResultModel
{
public string Name {get; set;}
public double Return {get; set;}
}

and code will be

if (response.IsSuccessStatusCode)
{
var stringData = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<ResultModel>(stringData);

var value=result.Return;
var name=Result.Name;

}


Related Topics



Leave a reply



Submit