Monday, October 31, 2016

Make an HttpContent child for an HttpClient and add a header too.

I wanted to do something like this, but it took a bit of a different shape...

using System;
using System.Net.Http;
using System.Text;
using System.Web.Mvc;
using System.Web.Script.Serialization;
namespace HPS.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index()
      {
         using (var client = new HttpClient())
         {
            var package = new { Foo = "bar", Baz = "qux" };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var json = serializer.Serialize(package);
            Uri uri = new Uri("http://www.example.com/api/toucheme/");
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            content.Headers.Add("X-EXTRA", "whatever");
            var response = client.PostAsync(uri, content).Result;
         }
         return View();
      }
   }
}

 
 

Note that the second parameter for the .PostAsync is an HttpContent and you cannot just new one of these up. It's an abstract class and you need an actor that inherits from it. In the case of the StringContent (our actor) I recommend having all three parameters I specify to avoid 415 (unsupported media type) errors.

No comments:

Post a Comment