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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16585479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:22:24  来源:igfitidea点击:

How can i find APIs for a weather forcast websites?

javaxmlapiweather-apiyahoo-weather-api

提问by Muhammed Refaat

I making a java application that give the user notification with the weather conditions. i used the yahoo weather API provided by yahoo like that link :

我制作了一个 Java 应用程序,向用户提供天气情况通知。我使用了 yahoo 提供的 yahoo 天气 API,如该链接:

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

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

and all i have to do is to change the eight numbered code that is in the URL in order to change the city.

我所要做的就是更改 URL 中的八个编号代码以更改城市。

that's working perfect, but there are two problems facing me now:

这工作完美,但我现在面临两个问题:

the first one, i want to implement a lot of weather forecast sources in my application not just the yahoo weather and i can't find a similar service in any other weather forecast websites.

第一个,我想在我的应用程序中实现很多天气预报源,而不仅仅是雅虎天气,我在任何其他天气预报网站上都找不到类似的服务。

the second one, i want to obtain the codes of all the cities in yahoo weather as for sure i won't ask the user to enter his city code, but to enter his city name and i'll match it with the code.

第二个,我想获取雅虎天气中所有城市的代码,因为我肯定不会要求用户输入他的城市代码,而是输入他的城市名称,我会将其与代码匹配。

and here is the code that works with me in java:

这是在Java中与我一起使用的代码:

the code to return the XML file:

返回 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;
        }
    }

the code to display the temperature and humidity in that city :

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

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();
        }
    }

}

回答by beddamadre

You can use Metwit weather apisimply passing latitude and longitude.
If you can implement them client-side: 200 request/day (ip based throttling) no authentication required. Worldwide coverage, JSON and REST compliant. You can register for extra API calls for free and if you still need it to call them server side the basic plan is pretty cheap.

您可以使用 Metwit天气 api简单地传递纬度和经度。
如果您可以在客户端实现它们:200 个请求/天(基于 ip 的限制)无需身份验证。全球覆盖,JSON 和 REST 兼容。你可以免费注册额外的 API 调用,如果你仍然需要它来调用它们服务器端,基本计划非常便宜。

Full disclosure: I own this API.

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

回答by Sai

You can use YQL (yahoo query language) to find the WOEID by city name like

您可以使用 YQL(雅虎查询语言)按城市名称查找 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=?";

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=?";

回答by bercik

I know this is an old question, but i found it and as Sai suggested i have written code in java that send YQL query and retrieve WOEID number. Than it uses it to get weather from yahoo-weather-java-api. It needs gsondependecy which you can get by adding dependency to maven. I hope this will help someone.

我知道这是一个老问题,但我找到了它,正如 Sai 建议的那样,我已经用 Java 编写了代码,可以发送 YQL 查询并检索 WOEID 号。比它使用它从yahoo-weather-java-api获取天气。它需要gson依赖,你可以通过向 maven 添加依赖来获得它。我希望这会帮助某人。

EDIT

编辑

If there is more than one WOEID number for given town name, than getWeather returns weather for town with first WOEID returned.

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

CODE

代码

Weather.java:

天气.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:

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);
    }
}

回答by AlexR

Take a look on this discussion. It seems relevant:

看看这个讨论。似乎相关:

https://stackoverflow.com/questions/4876800/is-there-an-international-weather-forecast-api-that-is-not-limited-for-non-comme

https://stackoverflow.com/questions/4876800/is-there-an-international-weather-forecast-api-that-is-not-limited-for-non-comme

Additionally type "weather forecast api" in google. There are tons of references to APIs that support several weather services.

另外在谷歌中输入“天气预报api”。有大量对支持多种天气服务的 API 的引用。

回答by Cormac Driver

Here's a list of Weather APIs that are available via the Temboo Java SDK:

以下是可通过 Temboo Java SDK 获得的 Weather API 列表:

https://temboo.com/library/keyword/weather/

https://temboo.com/library/keyword/weather/

回答by acriel

As for the first question, I've build a website using forecast.io. It's pretty good. Good API and 1000 free calls/day. It uses latitute/longitude to find the weather of a place.

对于第一个问题,我已经建立使用网站forecast.io。这是相当不错。良好的 API 和每天 1000 次免费调用。它使用纬度/经度来查找一个地方的天气。

As for the second question, I would resolve what the user puts in with the Google GeocodingApi. So when they search for "New York", you check if you already have the relevant coordinates in your database, otherwise, you do an API call to Google Geocoding.

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