0

i'm trying to send a post request to an online API to recieve net data, it was succesfull with normal key-value's but not with array's as value and i could't find it on the internet without creating a big amount of extra classes.

This is how i tried to post to the url with normal data (the 3th one needs an array in stead of a single object).

 IEnumerable<KeyValuePair<string, string>> queries = new List<KeyValuePair<string, string>>()
        {
               new KeyValuePair<string, string>("keyA","ValueA"),
               new KeyValuePair<string, string>("keyB", ""),
               new KeyValuePair<string, string>("KeyC", "ValueCDE"), //array
        };
        HttpContent q = new FormUrlEncodedContent(queries);
        Console.WriteLine(q.ToString());
        using (HttpClient client = new HttpClient())
        {
            using (HttpResponseMessage response = await client.PostAsync(url, q))
            {
                using (HttpContent content = response.Content)
                {
                    string mycontent = await content.ReadAsStringAsync();
                    HttpContentHeaders headers = content.Headers;
                    Console.WriteLine(mycontent);
                    Console.WriteLine(response);
                }
            }
        }

I tried to send raw data to the url but i recieved no response from it.

    async static void PostRawRequest(string url)
    {
        string rawr = @"{
       ""a"":""a"",
       ""b"":"""",
       ""c"": [""C"", ""D"",""F""],
       ""StickerColor"": ""red""
       }";

        string result = "";
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            result = client.UploadString(url, "POST", rawr);
        }
        Console.WriteLine(result);

}

Can anyone help me in either the first(sending array values) or second (sending raw data)?

2
  • Instead of trying to create a string by hand, just use Json.NET Commented Sep 21, 2017 at 14:07
  • You should probably drop WebClient too. It's been replaced by HttpClient which, btw can also serialize objects to Json Commented Sep 21, 2017 at 14:08

1 Answer 1

1

If you can, use a library to handle the serialization for you. Then you can do something like this (using Newtonsoft.Json):

using (var client = new HttpClient())
{
    var json = JsonConvert.SerializeObject(yourObject);
    client.PostAsync(yourUri, new StringContent(json, Encoding.UTF8, "application/json"));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.