How to call HttpClient.PostAsync with a query string

This has to be one of the most non-discoverable APIs ever, and annoyed the hell out of me earler today. Hence my posting it here so that others may not have to struggle over something so trivial.

All I want to do is post a query string to an URL asynchronously, but the second parameter, which is of type HttpContent, is a mystery that your average Google search does not unveil… (I eventually found the answer here on Rick Strahl’s blog.)

Let’s say you want to post to http://SomeUrl.somewhere with a query string of ThisIs=Annoying

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;

namespace Demo
{
    public class Example
    {
        public async void AsyncPost()
        {
            var values = new Dictionary<string, string>();
            values.Add("ThisIs", "Annoying");
            var content = new FormUrlEncodedContent(values);

            using (var client = new HttpClient())
            {
                try
                {
                    var httpResponseMessage = await client.PostAsync("http://SomeUrl.somewhere", content);

                    if (httpResponseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        // Do something...
                    }
                }
                catch (OperationCanceledException) { }
            }
        }
    }
}
Advertisements

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged . Bookmark the permalink.

7 Responses to How to call HttpClient.PostAsync with a query string

  1. Nexxkinn says:

    this is very useful for me, when i realised that Google Search becomes shittier and even shittier than bing search…
    thank you very much!

    Liked by 1 person

  2. Thanks Jerome !. I had a hard time today trying to get this to work and your blog post helped me.

    I’m using StringContent instead of FormUrlEncodedContent so I can simply serialize an object and pass it to the StringContent constructor.

    cheers
    Harold

    Liked by 1 person

  3. Yasitha says:

    How can I change this to post a string array instead of string values

    Like

    • Jerome says:

      Do you really want to pass an entire array as a query string? It makes more sense if you pass a few strings, instead of an array, and give each string a name.

      I suppose if you really wanted to be lazy, you could use a for loop through the array, using the index for each element’s key in the dictionary. Then encode the dictionary as in my example..

      Like

      • Yasitha says:

        I mean not a single string array. Consider I have three params. Two are strings and one is a string array. Anyway I was able to create a Object for this and I serialized it and sent.

        Liked by 1 person

  4. okg says:

    Thanks a lot! worked as expected!!

    Liked by 1 person

  5. Tom C says:

    Amen! I have been looking for this off and on for 2 days.
    Thanks for posting it.
    I’m constantly amazed at how bad Google search and MSDN documentation is.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s