建立查询字符串System.Net.HttpClient GET字符串、System、Net、HttpClient

2023-09-02 11:49:32 作者:决定忘记你

如果我希望提交使用System.Net.HttpClient似乎没有API添加参数的HTTP GET请求,这是正确的?

有没有什么简单的API可用于构建,不涉及建设一个名字的收藏价值和URL编码的,然后终于它们连接起来的查询字符串? 我希望能使用类似RestSharp的API(即AddParameter(..))

解决方案   

如果我希望提交使用System.Net.HttpClient HTTP GET请求   似乎有没有API添加的参数,这是正确的?

是的。

  

有没有什么简单的API可用于构建查询字符串   不涉及建设一个名字的收藏价值和URL编码   这些,最后串联呢?

肯定的:

  VAR的查询= HttpUtility.ParseQueryString(的String.Empty);
查询[富] =巴≤;>&安培; -baz;
查询[栏​​] =bazinga;
字符串查询字符串= query.ToString();
 
C windows diagnostics system Networking

会给你预期的结果是:

 富=栏%3C%3E%26巴兹和放大器;巴= bazinga
 

您还可能会发现 UriBuilder 类有用的:

  VAR建设者=新UriBuilder(http://example.com);
builder.Port = -1;
VAR的查询= HttpUtility.ParseQueryString(builder.Query);
查询[富] =巴≤;>&安培; -baz;
查询[栏​​] =bazinga;
builder.Query = query.ToString();
字符串URL = builder.ToString();
 

会给你预期的结果是:

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

,你可以多养活安全你的 HttpClient.GetAsync 方法。

If I wish to submit a http get request using System.Net.HttpClient there seems to be no api to add parameters, is this correct?

Is there any simple api available to build the query string that doesn't involve building a name value collection and url encoding those and then finally concatenating them? I was hoping to use something like RestSharp's api (i.e AddParameter(..))

解决方案

If I wish to submit a http get request using System.Net.HttpClient there seems to be no api to add parameters, is this correct?

Yes.

Is there any simple api available to build the query string that doesn't involve building a name value collection and url encoding those and then finally concatenating them?

Sure:

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

will give you the expected result:

foo=bar%3c%3e%26-baz&bar=bazinga

You might also find the UriBuilder class useful:

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();

will give you the expected result:

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

that you could more than safely feed to your HttpClient.GetAsync method.