如何查找天气预报网站的API?

4

我正在制作一个使用Java编写的应用程序,可以提醒用户天气状况。我使用了雅虎提供的天气API,链接如下:

http://weather.yahooapis.com/forecastrss?w=2502265

我只需要更改URL中的八位数字代码就可以更改城市。
这非常完美,但现在我面临两个问题:
第一个问题是,我想在我的应用程序中实现很多天气预报来源,而不仅仅是雅虎天气。但我无法在其他天气预报网站上找到类似的服务。
第二个问题是,我想获取雅虎天气中所有城市的代码,因为我肯定不会要求用户输入他的城市代码,而是要求他输入他的城市名称,然后我将与代码匹配。
以下是我在Java中使用的代码来返回XML文件:
package search;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

    public class Process {

        public static void main(String[] args) throws IOException {

            Display disp = new Display();

            Document doc = generateXML("1940345");
            disp.getConditions(doc);

        }

        public static Document generateXML(String code) throws IOException {

            String url = null;
            String XmlData = null;

            // creating the URL
            url = "http://weather.yahooapis.com/forecastrss?w=" + code;
            URL xmlUrl = new URL(url);
            InputStream in = xmlUrl.openStream();

            // parsing the XmlUrl
            Document doc = parse(in);

            return doc;

        }

        public static Document parse(InputStream is) {
            Document doc = null;
            DocumentBuilderFactory domFactory;
            DocumentBuilder builder;

            try {
                domFactory = DocumentBuilderFactory.newInstance();
                domFactory.setValidating(false);
                domFactory.setNamespaceAware(false);
                builder = domFactory.newDocumentBuilder();

                doc = builder.parse(is);
            } catch (Exception ex) {
                System.err.println("unable to load XML: " + ex);
            }
            return doc;
        }
    }

显示该城市温度和湿度的代码:

package search;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Display {

    static void getConditions(Document doc) {

        String city = null;
        String unit = null;

        try {

            doc.getDocumentElement().normalize();

            NodeList nList = doc.getElementsByTagName("rss");

            for (int temp = 0; temp < nList.getLength(); temp++) {

                Node nNode = nList.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element eElement = (Element) nNode;

                    NodeList nl = eElement
                            .getElementsByTagName("yweather:location");

                    for (int tempr = 0; tempr < nl.getLength(); tempr++) {

                        Node n = nl.item(tempr);

                        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                            Element e = (Element) n;
                            city = e.getAttribute("city");
                            System.out.println("The City Is : " + city);

                        }
                    }

                    NodeList nl2 = eElement
                            .getElementsByTagName("yweather:units");

                    for (int tempr = 0; tempr < nl2.getLength(); tempr++) {

                        Node n2 = nl2.item(tempr);

                        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                            Element e2 = (Element) n2;
                            unit = e2.getAttribute("temperature");

                        }
                    }

                    NodeList nl3 = eElement
                            .getElementsByTagName("yweather:condition");

                    for (int tempr = 0; tempr < nl3.getLength(); tempr++) {

                        Node n3 = nl3.item(tempr);

                        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                            Element e3 = (Element) n3;
                            System.out.println("The Temperature In " + city
                                    + " Is : " + e3.getAttribute("temp") + " "
                                    + unit);
                        }
                    }

                    NodeList nl4 = eElement
                            .getElementsByTagName("yweather:atmosphere");

                    for (int tempr = 0; tempr < nl4.getLength(); tempr++) {

                        Node n4 = nl4.item(tempr);

                        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                            Element e4 = (Element) n4;
                            System.out.println("The Humidity In " + city
                                    + " Is : " + e4.getAttribute("humidity"));
                        }
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
6个回答

2
您可以使用Metwit 天气API,只需传递纬度和经度即可。
如果您可以在客户端实现它们:每天200个请求(基于IP的限制),无需身份验证。全球覆盖范围,符合JSON和REST标准。您可以免费注册额外的API调用,如果您仍然需要在服务器端调用它们,则基本计划非常便宜。

完全公开披露:我拥有这个API。


1

我知道这是一个旧问题,但我发现它并且正如Sai建议的那样,我已经编写了Java代码来发送YQL查询并检索WOEID编号。然后它使用它从yahoo-weather-java-api获取天气。它需要gson依赖项,可以通过将依赖项添加到Maven中获取。我希望这会对某人有所帮助。

编辑

如果给定城镇名称有多个WOEID编号,则getWeather返回第一个返回的WOEID编号的城镇的天气。

代码

Weather.java:

import com.github.fedy2.weather.YahooWeatherService;
import com.github.fedy2.weather.data.Channel;
import com.github.fedy2.weather.data.unit.DegreeUnit;

import com.google.gson.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import javax.xml.bind.JAXBException;

/**
 *
 * @author robert
 */
public class Weather
{
    public Channel getWeather(String townName) throws CantFindWeatherException
    {
        try
        {
            String baseUrl = "http://query.yahooapis.com/v1/public/yql?q=";
            String query = 
                    "select woeid from geo.places where text=\"" + 
                    townName + "\"";
            String fullUrlStr = baseUrl + URLEncoder.encode(query, "UTF-8") + 
                    "&format=json";

            URL fullUrl = new URL(fullUrlStr);

            ResultObject resultObject = null;
            ResultArray resultArray = null;

            try (InputStream is = fullUrl.openStream(); 
                    InputStreamReader isr = new InputStreamReader(is); 
                    BufferedReader br = new BufferedReader(isr))
            {
                String result = "";
                String read;
                while ((read = br.readLine()) != null)
                {
                    result += read;
                }

                Gson gson = new Gson();
                try
                {
                    resultObject = gson.fromJson(result, ResultObject.class);
                }
                catch (com.google.gson.JsonSyntaxException ex)
                {
                    resultArray = gson.fromJson(result, ResultArray.class);
                }
            }

            Integer woeid = null;
            if (resultObject != null)
            {
                if (resultObject.query.results != null)
                {
                    woeid = resultObject.query.results.place.woeid;
                }
            }
            else if (resultArray != null)
            {
                woeid = resultArray.query.results.place[0].woeid;
            }

            if (woeid != null)
            {
                YahooWeatherService service = new YahooWeatherService();
                Channel channel = service.getForecast(woeid.toString(), 
                        DegreeUnit.CELSIUS);
                return channel;
            }
            else
            {
                throw new CantFindWeatherException();
            }
        }
        catch (IOException | JsonSyntaxException | JAXBException ex)
        {
            throw new CantFindWeatherException(ex);
        }
    }

    private static class ResultObject
    {
        public QueryObject query;
    }

    private static class ResultArray
    {
        public QueryArray query;
    }

    private static class QueryObject
    {
        public int count;
        public String created;
        public String lang;
        public ResultsObject results;
    }

    private static class QueryArray
    {
        public int count;
        public String created;
        public String lang;
        public ResultsArray results;
    }

    private static class ResultsObject
    {
        public Place place;
    }

    private static class ResultsArray
    {
        public Place[] place;
    }

    private static class Place
    {
        public int woeid;
    }
}

CantFindWeatherException.java:

/**
 *
 * @author robert
 */
public class CantFindWeatherException extends Exception
{
    public CantFindWeatherException()
    {
    }

    public CantFindWeatherException(String message)
    {
        super(message);
    }

    public CantFindWeatherException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public CantFindWeatherException(Throwable cause)
    {
        super(cause);
    }
}

1

我确实尝试过这样做,但我没有得到我想要的结果,因为如你在我的代码中看到的那样,我想要一个带有城市代码的URL,而我只是更改了代码,而谷歌搜索生成的网站并不支持。 - Muhammed Refaat

1

1
你可以使用YQL(Yahoo查询语言)通过城市名称查找WOEID,例如:

var lclqry = escape('select * from geo.places where text="OKLAHOMA CITY"') var lclurl = "http://query.yahooapis.com/v1/public/yql?q=" + lclqry + "&format=json&callback=?";

(注:WOEID是一个数字标识符,用于表示地理位置。)

0

关于第一个问题,我使用forecast.io构建了一个网站。它非常好用,API很好,每天可以免费调用1000次。它使用纬度/经度来查找某个地方的天气。

至于第二个问题,我会使用Google Geocoding API来解决用户输入的内容。所以当他们搜索“纽约”时,您可以检查您的数据库中是否已有相关坐标,否则,您可以调用Google Geocoding的API。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接