Search code examples
c#httpwebrequest

How to correctly send json with httpWebRequest?


I have a httpWebRequest object.

It is initialised like this:

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://myURL.com"); // This is actually my company URL I can't show
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

Then I want to send to this URL json datas. After tries, I figured I do it wrong, but I don't get what it is... Here is where I send it datas:

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            List<string> datas = new List<string>();
            datas.Add("1");


            string json = Newtonsoft.Json.JsonConvert.SerializeObject(datas);

            streamWriter.Write(json);
            streamWriter.Flush();
            streamWriter.Close();
        }

It doesn't seem to be working. Is there a way to catch the URL I'm sending? I tried Fiddler, but I don't see my request.

Also this code works with a chrome console:

jQuery.ajax({
                'url': 'http://myURL.com',  
                'type': 'POST',
                'data': {data:[7]},
                'success': function (data) {
                    console.log(data);
                }
            });

Solution

  • From the code you use at Chrome it is denoted your data structure is not correct.

    First, you need a class to store the data, lets call it DataHolder:

    public class DataHolder
    {
        public int[] data { get; set; }
    }
    

    So now you need to fill it:

    var newData = new DataHolder{ data = new int[] { 1 } };
    

    And now you can serialize it and it should work:

    string json = Newtonsoft.Json.JsonConvert.SerializeObject(newData);
    

    EDIT: as a note, in a previous question you posted you tried to send "{ data: [1] }" which is incorrect, it should be "{ \"data\": [1] }" but better stick to a class with the correct structure and let the serializer deal with those implementation details.