4

我制作了一个 java 应用程序,向用户提供天气状况通知。我使用了 yahoo 提供的 yahoo 天气 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();
        }
    }

}
4

6 回答 6

2

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

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

于 2013-05-20T21:19:04.383 回答
1

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

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

于 2013-05-16T13:26:10.477 回答
1

您可以使用 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=?";

于 2013-06-26T20:53:35.360 回答
1

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

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

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

于 2013-05-16T10:55:25.507 回答
1

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

编辑

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

代码

天气.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);
    }
}
于 2015-05-30T12:22:20.397 回答
0

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

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

于 2013-05-16T10:57:30.613 回答