'HTTP Post request method does not execute. How to use HttpClient?

I'm trying to make a post request using HttpClient. The expected json which I'm trying to post is stored in var result and looks like :

{
  "ID": 142,
  "StationNo": 19,
  "RunTime": 1800,
  "ControllerID": 4,
  "ControllerAddress": 2,
  "ProgramNo": 5,
  "ModeID": "AutoProgram",
  "EventDate": "2022-04-27T22:30:02",
  "Description": "Irrigation Completed",
  "MessageCode": 5,
  "time": "2022-05-06T08:58:41.322Z",
  "source": {
    "id": "43432088"
  },
  "type": "c8y_Golf_Controller",
  "text": "PilotCC Data New Msg"
}

The foreach loop runs for 4 iterations but no successful request is made. It just returns nothing in response. I've tested the above json in postman and it works fine there.

Here's my sample code :


using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Net.Mime;
using System.Net.Http.Json;



namespace ObjFromJson
{
    public class Program
    {
        static async Task Main(string[] args)
        {

            string json = @"{
            'Values': [
                {
                    'MsgSource': null,
                    'TagName': 'Data.New_MSG',
                    'RawValue': '[\r\n  {\r\n    \'ID\': 145,\r\n    \'StationNo\': 6,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 2,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T23:30:02\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  },\r\n  {\r\n    \'ID\': 144,\r\n    \'StationNo\': 18,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 5,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T22:00:00\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  },\r\n  {\r\n    \'ID\': 143,\r\n    \'StationNo\': 15,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 4,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T22:00:02\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  },\r\n  {\r\n    \'ID\': 142,\r\n    \'StationNo\': 19,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 5,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T22:30:02\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  }\r\n]',
                    'ScaledValue': '[\r\n  {\r\n    \'ID\': 145,\r\n    \'StationNo\': 6,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 2,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T23:30:02\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  },\r\n  {\r\n    \'ID\': 144,\r\n    \'StationNo\': 18,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 5,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T22:00:00\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  },\r\n  {\r\n    \'ID\': 143,\r\n    \'StationNo\': 15,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 4,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T22:00:02\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  },\r\n  {\r\n    \'ID\': 142,\r\n    \'StationNo\': 19,\r\n    \'RunTime\': 1800,\r\n    \'ControllerID\': 4,\r\n    \'ControllerAddress\': 2,\r\n    \'ProgramNo\': 5,\r\n    \'ModeID\': \'AutoProgram\',\r\n    \'EventDate\': \'2022-04-27T22:30:02\',\r\n    \'Description\': \'Irrigation Completed\',\r\n    \'MessageCode\': 5\r\n  }\r\n]',
                    'Status': 'Normal',
                    'ComStatus': null,
                    'TimeStamp': '2022-04-28 13:17:39.851'
                }
                ]
            }";
            Root root = JsonConvert.DeserializeObject<Root>(json);
            string rawValue = root.Values[0].RawValue;
            JArray array = JArray.Parse(rawValue);
            string isoTime = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
            string json2 =    $"{{\"time\": \"{isoTime}\",\"source\": {{\"id\": \"43432088\" }},\"type\": \"c8y_Golf_Controller\",\"text\": \"PilotCC Data New Msg\"}}";
            JObject json3 = JObject.Parse(json2);
            var result = new JObject();
            foreach(var item in array)
            {
                result.Merge(item);
                result.Merge(json3);
                
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic","base64authvalue");
                    
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.com.nsn.cumulocity.event+json"));
                    JsonContent myContent = JsonContent.Create(result);
                    HttpResponseMessage response = await client.PostAsync("https://myurl.com", myContent);
                    var responseString = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseString);
                }
             
            }

        }
        
        public class Root
        {
            public List<Value> Values {get; set;}
        }
        public class Value
        {
            public string RawValue { get; set; }
        }       
    }   
}

EDIT : Added Console.Write((int)response.StatusCode); just before Console.WriteLine(responseString); and it's returning Error code: 415

There are few important things to consider while making the request :

    The Content-Type must be "application/json"
    It must have Accept header with value as "application/vnd.com.nsn.cumulocity.event+json"
    Basic auth must be used

I'm handeling all these things and the JSON which is in var result is also in correct format (tested in postman) then what else am I missing here?



Solution 1:[1]

With a little more research, after spending entire day to make this work I was finally able to get it done. As for this particular problem which I have raised here, it's because the Content-Type becomes application/json; charset=utf-8 which can raise unsupported media type error.

I added string json4 = JsonConvert.SerializeObject(result); after result.Merge(json3); line in foreach loop and replaced the line JsonContent myContent = JsonContent.Create(result); with var stringContent = new StringContent(json4, Encoding.UTF8, MediaTypeNames.Application.Json); stringContent.Headers.ContentType.CharSet = "";

This removes the charset from your Content-Type header.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1