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
Release: 2025-01-09 09:56:43
Original
953 people have browsed it

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>
Copy after login

This produces:

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

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>
Copy after login

Resulting in:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template