因此,在学习了一些教程并使用https://openweathermap.org/current之后,我编写了一些代码,现在我花了几个小时试图找出它不起作用的原因。我首先制作了一个 Windows 窗体应用程序并制作了这个界面。起初它能够找到你输入的任何城市的天气,但我在 openweathermap 上找不到这样的选项,所以我只将其限制在韩国首尔。但是我不明白为什么当我单击按钮时没有任何反应,我认为它应该在文本框中带回预测。如果有人可以提供帮助,我将非常感激。
这是我的完整代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Net;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string city;
city = txtcity.Text;
string uri = string.Format("http://api.openweathermap.org/data/2.5/weather?q=Seoul&mode=xml&appid=78dff84492be32f8b4f77692904607a1", city);
XDocument doc = XDocument.Load(uri);
string iconUri = (string)doc.Descendants("icon").FirstOrDefault();
WebClient client = new WebClient();
string maxtemp = (string)doc.Descendants("temperature.max").FirstOrDefault();
string mintemp = (string)doc.Descendants("temperature.min").FirstOrDefault();
string maxwindm = (string)doc.Descendants("maxwind_mph").FirstOrDefault();
string maxwindk = (string)doc.Descendants("maxwind_kph").FirstOrDefault();
string humidity = (string)doc.Descendants("avghumidity").FirstOrDefault();
string country = (string)doc.Descendants("country").FirstOrDefault();
string cloud = (string)doc.Descendants("text").FirstOrDefault();
txtmaxtemp.Text = maxtemp;
txtmintemp.Text = mintemp;
txtwindm.Text = maxwindm;
txtwindk.Text = maxwindk;
txthumidity.Text = humidity;
label7.Text = cloud;
txtcountry.Text = country;
}
private void button1_Click(object sender, EventArgs e)
{
}
}
}
您已在链接中刻录了您要查询某个城市(首尔)的信息:
“http://api.openweathermap.org/data/2.5/weather?q***=Seoul***&mode=xml&appid=78dff84492be32f8b4f77692904607a1”
您的代码中没有任何信息表明您在此链接中更改了它。请尝试这个:
String.Format("http://api.openweathermap.org/data/2.5/weather?q={0}&mode=xml&appid=78dff84492be32f8b4f77692904607a1",city);
希望一切顺利:)