Home >Backend Development >C++ >How to Efficiently Build Query Strings for System.Net.HttpClient GET Requests?

How to Efficiently Build Query Strings for System.Net.HttpClient GET Requests?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-09 09:56:43906browse

How to Efficiently Build Query Strings for System.Net.HttpClient GET Requests?

Crafting Query Strings for System.Net.HttpClient GET Requests

System.Net.HttpClient's GET requests lack a direct parameter-adding method, but constructing query strings is straightforward. Here are two efficient approaches:

First, leverage HttpUtility.ParseQueryString to avoid manual name-value pair construction:

<code class="language-csharp">var query = HttpUtility.ParseQueryString(string.Empty);
query["foo"] = "bar&-baz";
query["bar"] = "bazinga";
string queryString = query.ToString();</code>

This produces:

<code>foo=bar%3c%3e%26-baz&bar=bazinga</code>

Alternatively, use the UriBuilder class for complete URI customization:

<code class="language-csharp">var builder = new UriBuilder("http://example.com");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["foo"] = "bar&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();</code>

Resulting in:

<code>http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga</code>

Both HttpUtility.ParseQueryString and UriBuilder offer clean, efficient solutions for building query strings within System.Net.HttpClient GET requests.

The above is the detailed content of How to Efficiently Build Query Strings for System.Net.HttpClient GET Requests?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn