如何在GET请求中使用用户输入的变量?

时间:2018-01-05 18:15:13

标签: c#

我需要输入用户输入的字符串,并将其作为搜索查询发送到名为WordTracker的搜索引擎API的GET请求中。我将搜索查询硬编码到请求中并且有效。遗憾的是,我不太了解API,我正在学习。怎么会去做这个任务?

我的代码,使用api文档:

var baseAddress = new Uri("http://api3.wordtracker.com");

using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
     httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");

     using (var response = await httpClient.GetAsync(requestUri: "search/stats?keywords[]=token&app_id=d******4&app_key=d*****d)
     {
           string responseData = await response.Content.ReadAsStringAsync();
     }
}

2 个答案:

答案 0 :(得分:0)

我认为这就是你想要的,所以它不是硬编码的标记:

var keyWord = "KEYWORDTOSEARCH"; # you'd replace this

var baseAddress = new Uri("http://api3.wordtracker.com");
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
 httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept", "application/json");
using (var response = await httpClient.GetAsync(requestUri: "search/stats?keywords[]=" + keyWord  + "&app_id=d******4&app_key=d*****d)
{
string responseData = await response.Content.ReadAsStringAsync();
}
}

答案 1 :(得分:0)

虽然有一个明确的答案,我认为更好的解决方案是

var url = String.Format("search/stats?keywords[]={0}&app_id={1}&app_key={2}",
     keyword,id,key);
using (var response = await httpClient.GetAsync(requestUri: url)

一旦你超越了一个变量,通过+建立字符串是凌乱的。

最新的c#版本也有

var url = $"search/stats?keywords[]={keyword}&app_id={id}&app_key={key}";