June 30th, 2022

How can I build a URL query string in the Windows Runtime?

Last time, we looked at a Windows Runtime helper object for parsing URL query strings. It also has a helper object for building URL query strings, but for some reason the two aren’t in the same place.

In C#, you can use a FormUrlEncodedContent. In the Windows Runtime, a similar function is provided by the HttpFormUrlEncodedContent class. The oddity is that the query parser is in the Windows.Foundation namespace, but the query builder is in the Windows.Web.Http namespace. My guess is that query parsing is something procotol handlers need to do, whereas query building is something you typically do only when dealing with HTTP servers.

Anyway, here’s the HttpFormUrlEncodedContent class:

std::map<hstring, hstring> content;
content.emplace(L"v", L"dQw4w9WgXcQ");
content.emplace(L"t", L"43s");
auto encoder = HttpFormUrlEncodedContent(content);
auto encoded = encoder.ToString();

You can optimize this by using the initializer_list constructor for std::map:

std::map<hstring, hstring> content{
    { L"v", L"dQw4w9WgXcQ" },
    { L"t", L"43s" },
};
auto encoder = HttpFormUrlEncodedContent(content);
auto encoded = encoder.ToString();

But wait, we can do better: We don’t need a std::map at all. The Http­Form­Url­Encoded­Content constructor takes an IIterator<IKeyValuePair<hstring, hstring>>, and C++/WinRT allows you to pass, among other things, a std::initializer_list<std::pair<hstring, hstring>>. Those are easy to make on the fly:

auto encoder = HttpFormUrlEncodedContent({
    { L"v", L"dQw4w9WgXcQ" },
    { L"t", L"43s" },
});
auto encoded = encoder.ToString();

And now you can make it a one-liner:

auto encoded = HttpFormUrlEncodedContent({
    { L"v", L"dQw4w9WgXcQ" },
    { L"t", L"43s" },
}).ToString();

Note that the Http­Form­Url­Encoded­Content builds a query string. Don’t use it for encoding the base URL or the fragment. Those follow different rules.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

1 comment

Discussion is closed. Login to edit/delete existing comments.

  • Daniel White

    Thanks for the Rick Roll