How can I build a URL query string in the Windows Runtime?
source link: https://devblogs.microsoft.com/oldnewthing/20220630-00/?p=106805
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
How can I build a URL query string in the Windows Runtime?
Raymond Chen
June 30th, 20221
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 HttpFormUrlEncodedContent
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();
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK