Quantcast
Channel: briancaos – Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 276

HttpClient POST or PUT Json with content type application/json

$
0
0

The HttpClient is a nifty tool for getting and sending data to a URL, but it works differently from the old fashioned WebRequest class.

The content type is added to the post data instead of added as a header parameter. So if you with to PUT or POST Json data, and you need to set the content type to application/json, specify the content type in the parameters of the StringContent that you POST:

string json;

var content = new StringContent(
  json, 
  System.Text.Encoding.UTF8, 
  "application/json"
  );

An example of a complete POST method that can take an object and POST it as Json could look like this:

using System.Net.Http;
using Newtonsoft.Json;

private static HttpClient _httpClient = new HttpClient();

public bool POSTData(object json, string url)
{
  using (var content = new StringContent(JsonConvert.SerializeObject(json), System.Text.Encoding.UTF8, "application/json"))
  {
    HttpResponseMessage result = _httpClient.PostAsync(url, content).Result;
    if (result.StatusCode == System.Net.HttpStatusCode.Created)
      return true;
    string returnValue = result.Content.ReadAsStringAsync().Result;
    throw new Exception($"Failed to POST data: ({result.StatusCode}): {returnValue}");
  }
}

This method is not utilizing the async properties of the HttpClient class. Click here to see how to use HttpClient with async.

MORE TO READ:


Viewing all articles
Browse latest Browse all 276

Trending Articles