Search code examples
c#jsonhttpclientjson-serialization

HttpClient postasync with custom header and application/json for body C#


Hello I want to run push app center from its api. But I don't know how to make the proper format.

I want to postasync from this api: https://appcenter.ms/api/v0.1/apps/KacangIjo/ShopDiaryApp/push/notifications

What it needs for Headers is: X-API-Token ="{api token}" and Content Type="application/json"

For the body(content) I want to put this:

{
    "notification_content" : {
        "name" : "Campaign Name",
        "title" : "Expired Warning",
        "body" : "You have items that almost expired"
    }
}

I have difficulties how to write in the correct format for HttpClient. I tried this and no work..

Content = new Content
{
   Name = "Campaign Name",
   Title = "Expired Warning",
   Body = "You have items that almost expired"
};
using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
{
   var myContent = JsonConvert.SerializeObject(data);
   client.DefaultRequestHeaders.Add("X-API-Token", "{my api token}");
   client.DefaultRequestHeaders.Accept.Add(new 
   MediaTypeWithQualityHeaderValue("application/json"));
   var builder = new UriBuilder(new Uri("https://appcenter.ms/api/v0.1/apps/KacangIjo/ShopDiaryApp/push/notifications"));
   HttpResponseMessage response = await client.PostAsync(builder.Uri, content);
};

But I know this code:

 {
        "notification_content" : {
            "name" : "Campaign Name",
            "title" : "Expired Warning",
            "body" : "You have items that almost expired"
        }
    }

is not same with this to convert the json format:

Content = new Content
{
    Name = "Campaign Name",
    Title = "Expired Warning",
    Body = "You have items that almost expired"
};

Can help me with the correct Serialize Json Format? and the correct format of httpclient header and body? I already found lot of sample but still no clue with the one that I want. Really appreciate your help guys :)


Solution

  • You need to structure your objects similar to your required JSON.

    Create classes like below.

    public class NotificationContent
    {
        [JsonProperty("name")]
        public string Name { get; set; }
    
        [JsonProperty("title")]
        public string Title { get; set; }
    
        [JsonProperty("body")]
        public string Body { get; set; }
    }
    
    public class PostObject
    {
        [JsonProperty("notification_content")]
        public NotificationContent NotificationContent { get; set; }
    }
    

    Above is the right structure, now when you will call JsonConvert.SerializeObject, your json will be

     {
        "notification_content" : {
            "name" : "Campaign Name",
            "title" : "Expired Warning",
            "body" : "You have items that almost expired"
        }
    } 
    

    Below is the code for http call

    using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) })
        {
            PostObject postObject = new PostObject
            {
                NotificationContent = new NotificationContent
                {
                    Name = "Campaign Name",
                    Title = "Expired Warning",
                    Body = "You have items that almost expired"
                }
            };
    
            var myContent = JsonConvert.SerializeObject(postObject);
            client.DefaultRequestHeaders.Add("X-API-Token", "{my api token}");
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            var builder = new UriBuilder(new Uri("https://appcenter.ms/api/v0.1/apps/KacangIjo/ShopDiaryApp/push/notifications"));
    
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, builder.Uri);
            request.Content = new StringContent(myContent, Encoding.UTF8, "application/json");//CONTENT-TYPE header
    
            HttpResponseMessage response = await client.SendAsync(request);
        };