本文介绍了建立查询字符串System.Net.HttpClient GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

是的。

肯定的:

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

会给你预期的结果是:

 富=栏%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(..))

解决方案

Yes.

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.

这篇关于建立查询字符串System.Net.HttpClient GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 15:17