Home > Backend Development > C++ > How Can I Easily Build Query Strings for System.Net.HttpClient GET Requests?

How Can I Easily Build Query Strings for System.Net.HttpClient GET Requests?

Patricia Arquette
Release: 2025-01-09 09:41:42
Original
413 people have browsed it

How Can I Easily Build Query Strings for System.Net.HttpClient GET Requests?

Query string construction method for System.Net.HttpClient GET request

Question:

System.Net.HttpClient lacks API to directly add GET request parameters. Is there an easier way to build query strings without manually creating name-value collections, URL encoding, and concatenation?

Answer:

Yes. Easily build query strings with no manual effort:

<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 will generate the following query string:

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

Alternatively, utilizing the UriBuilder class provides a more comprehensive solution:

<code class="language-csharp">// 为目标URL创建一个UriBuilder
var builder = new UriBuilder("http://example.com");
builder.Port = -1;

// 解析查询字符串
var query = HttpUtility.ParseQueryString(builder.Query);

// 添加参数
query["foo"] = "bar&-baz";
query["bar"] = "bazinga";

// 更新UriBuilder的查询字符串
builder.Query = query.ToString();

// 获取完整的URL
string url = builder.ToString();</code>
Copy after login

This method generates the following URL:

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

You can seamlessly integrate this URL into the GetAsync method of System.Net.HttpClient to perform a GET request with the required query parameters.

The above is the detailed content of How Can I Easily 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