【问题标题】:How to pass a variable in url in c#如何在c#中传递url中的变量
【发布时间】:2014-12-24 14:29:28
【问题描述】:

我正在尝试将字符串传递到 C# 中的 url:

using (var client = new WebClient())
{
  var responseStr = client.DownloadString("http://api.openweathermap.org/data/2.5 /weather?q=Groningen,nl&APPID=%207b030ffcc7338cc5f1adc4ca8e6205aa");          
}

我有一种方法可以传递字符串变量,而不是 ?q=Groningen 所以我可以使用文本字段来获取城市的天气。

我找不到答案。

谢谢

【问题讨论】:

  • "...q=" + yourStringVariable + "&APP..."
  • 为什么不使用字符串连接?你遇到问题了吗?

标签: c# .net variables url


【解决方案1】:

在 C# 中,您可以使用 + 运算符来连接字符串。

所以你可以使用类似下面的东西,

using (var client = new WebClient())
{
  var responseStr = client.DownloadString("http://api.openweathermap.org/data/2.5 /weather?q="+CHOICE+",nl&APPID=%207b030ffcc7338cc5f1adc4ca8e6205aa");          
}

CHOICE 是您想要的位置的变量。

有关连接的更多信息:here

【讨论】:

  • 谢谢。有效。我以前试过。但后来蓝线网址不再是 100%。所以我认为这行不通。我认为我需要 Request.Querie。
【解决方案2】:

您可以使用字符串连接来做到这一点:

var url = "http://.....q="+city+"&....."; 
var responseStr = client.DownloadString(url);  

其中city 是保存您要经过的城市的变量。

【讨论】:

    【解决方案3】:
    Webclient client = new Webclient();
    string city = "Lahore";
    string appId = "123456789";
    string url = "http://api.openweathermap.org/data/2.5/weather?APPID="+appId+"&q="+city+"";
    var json = client.DownloadString(json);
    

    现在根据您的要求反序列化 josn 响应。

    使用以下任何方式

    1. JavaScriptSerializer
    2. JSON.Net 库
    3. DataContractJsonSerializer

    【讨论】:

      猜你喜欢
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多