2014-05-08 107 views
1

我使用HttpClient.GetAsync()方法。我有一个类别列表,并希望在查询字符串中传递它。传递查询字符串中的最佳方式HttpClient.GetAsync()

var categories = new List<int>() {1,2}; 

如何在查询字符串中传递List<int>/List<string>?例如,https://example.com/api?categories=1,2

当然,可以使用foreachStringBuilder。但也许有更好的方法来做到这一点?

例如,.PostAsync(工作)和JSON内容非常方便:

var categories = new List<int>() {1,2}; //init List 
var parametrs = new Dictionary<string, object>(); 
parametrs.Add("categories", categories); 
string jsonParams = JsonConvert.SerializeObject(parametrs); // {"categories":[1,2]} 
HttpContent content = new StringContent(jsonParams, Encoding.UTF8, "application/json"); 
var response = await httpClient.PostAsync(new Uri("https://example.com"), content);   

附:我使用Windows Phone 8.

+0

您的代码显示您已经使用JSON传递内容。为什么不将查询字符串中的列表作为JSON传递?毕竟,JSON是用字符串表示数据的好方法。我刚才问过[如果在URL中传递JSON时会出现问题](http://stackoverflow.com/questions/22852270/potential-problems-with-passing-json-in-url),结果令人鼓舞。 – mason

+0

而不是循环和'StringBuilder',只需使用'string.Join(“,”,categories)'。 –

+0

@mason如何使用GetAsync()在查询字符串中传递json?对不起,我不太明白。 – Alexandr

回答

2

如果您准备依赖于支持URI模板的库,如我创建的库(http://www.nuget.org/packages/Tavis.UriTemplates/),那么您可以获得创建URI的各种灵活性。完整的规格是这里RFC6570

首先创建一个URI模板,

var template = new UriTemplate("http://example.com/api{?categories}"); 

,你可与一个简单的字符串,字符串列表或字符串键/值对的字典中设置的参数。

var idList = new string[] {"1", "4", "5", "7", "8"}; 
template.SetParameter("id",idList); 

,然后就可以解决这个参数来创建一个完整的URI

var uri = template.Resolve(); 
    Debug.Assert(uri == "http://example.com/api?categories=1,4,5,7,8"); 

的好处是,如果你有其他的查询参数,或有需要编码的字符,URI模板处理器将为您照顾所有这一切。

This扩展测试套件让您了解一些支持的疯狂内容。

相关问题