一个简单的java天气预报

我们看见许多网站首页都有天气的导航,但到底是怎么样实现的呢?学习了WebService和XML解析后我给您讲解如下:

1、创建一个基本类WeatherObj,代码如下:

package com.hnwater.business.weather;
import java.util.Hashtable;

/**
 *
 * @author gulin
 *
 */
public class WeatherObj {
    public static final String REGIONFIRST = "_regionFirst";// 上级行政区
    public static final String REGIONSECOND = "_regionSecond";// 本级行政区
    public static final String REGIONID = "_regionId";// 行政区id
    public static final String REGIONPIC = "_regionPic";// 行政区图片
    public static final String REPORTTIME = "_reportTime";// 最新上报时间
    public static final String TODAYTEMPERATURE = "_todayTemperature";// 今天温度
    public static final String TODAYDATE = "_todayDate";// 今天日期
    public static final String TODAYWIND = "_todayWind";// 今天风况
    public static final String TODAYPIC_1 = "_todayPic_1";// 今天天气图片1
    public static final String TODAYPIC_2 = "_todayPic_2";// 今天天气图片2
    public static final String TODAYDETAIL = "_todayDetail";// 今天天气实况
    public static final String ZHISHU = "_zhiShu";// 各个指数
    public static final String CHUANYIZHISHU = "穿衣指数:";
    public static final String GANMAOZHISHU = "感冒指数:";
    public static final String YUNDONGZHISHU = "运动指数:";
    public static final String XICHEZHISHU = "洗车指数:";
    public static final String LIANGSHAIZHISHU = "晾晒指数:";
    public static final String LVYOUZHISHU = "旅游指数:";
    public static final String LUKUANGZHISHU = "路况指数:";
    public static final String SHUSHIDUZHISHU = "舒适度指数:";
    public static final String TOMORROWTEMPERATURE = "_tomorrowTemperature";// 明天温度
    public static final String TOMORROWDATE = "_tomorrowDate";// 明天日期
    public static final String TOMORROWWIND = "_tomorrowWind";// 明天风况
    public static final String TOMORROWPIC_1 = "_tomorrowPic_1";// 明天天气图片1
    public static final String TOMORROWPIC_2 = "_tomorrowPic_2";// 明天天气图片2
    public static final String AFTERTOMORROWTEMPERATURE = "_affterTomorrowTemperature";// 后天温度
    public static final String AFTERTOMORROWDATE = "_affterTomorrowDate";// 后天日期
    public static final String AFTERTOMORROWWIND = "_affterTomorrowWind";// 后天风况
    public static final String AFTERTOMORROWPIC_1 = "_affterTomorrowPic_1";// 后天天气图片1
    public static final String AFTERTOMORROWPIC_2 = "_affterTomorrowPic_2";// 后天天气图片2
    public static final String DESCRIPT = "_descript";// 本地介绍

    public static final Hashtable<Integer, String> input = new Hashtable<Integer, String>(
            0);// 常量与数量对应

    static {
        input.put(0, REGIONFIRST);
        input.put(1, REGIONSECOND);
        input.put(2, REGIONID);
        input.put(3, REGIONPIC);
        input.put(4, REPORTTIME);

        input.put(5, TODAYTEMPERATURE);
        input.put(6, TODAYDATE);
        input.put(7, TODAYWIND);
        input.put(8, TODAYPIC_1);
        input.put(9, TODAYPIC_2);
        input.put(10, TODAYDETAIL);

        input.put(11, ZHISHU);

        input.put(12, TOMORROWTEMPERATURE);
        input.put(13, TOMORROWDATE);
        input.put(14, TOMORROWWIND);
        input.put(15, TOMORROWPIC_1);
        input.put(16, TOMORROWPIC_2);

        input.put(17, AFTERTOMORROWTEMPERATURE);
        input.put(18, AFTERTOMORROWDATE);
        input.put(19, AFTERTOMORROWWIND);
        input.put(20, AFTERTOMORROWPIC_1);
        input.put(21, AFTERTOMORROWPIC_2);

        input.put(22, DESCRIPT);
    }

    private String name;
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

2、创建一个工具类WeatherUtil,实现请求和解析WebService返回的数据,代码如下:

package com.hnwater.business.weather;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author gulin
 *
 */
public class WeatherUtil {
    private String encoding = "GBK";
    private String webServiceUrl = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";

    public static WeatherUtil getInstance() {
        return new WeatherUtil();
    }

    /**
     * 获取SOAP的请求头,并替换其中的标志符号为用户输入的城市
     *
     * @param city用户输入的城市名称
     * @return 客户将要发送给服务器的SOAP请求
     */
    private String getSoapRequest(String city) {
        StringBuilder sb = new StringBuilder();
        sb.append("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
        sb.append("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
        sb.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
        sb.append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
        sb.append("<soap:Body>");
        sb.append("<getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">");
        sb.append("<theCityName>");
        sb.append(city);
        sb.append("</theCityName>");
        sb.append("</getWeatherbyCityName>");
        sb.append("</soap:Body>");
        sb.append("</soap:Envelope>");
        return sb.toString();
    }

    /**
     * 用户把SOAP请求发送给服务器端,并返回服务器点返回的输入流
     *
     * @param city用户输入的城市名称
     * @return 服务器端返回的输入流,供客户端读取
     * @throws Exception
     */
    private InputStream getSoapInputStream(String city) throws Exception {
        try {
            String soap = getSoapRequest(city);
            if (soap == null) {
                return null;
            }
            URL url = new URL(webServiceUrl);
            URLConnection conn = url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
            conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
            conn.setRequestProperty("SOAPAction","http://WebXml.com.cn/getWeatherbyCityName");
            
            OutputStream os = conn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
            osw.write(soap);
            osw.flush();
            osw.close();

            InputStream is = conn.getInputStream();
            return is;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 对服务器端返回的XML进行解析
     *
     * @param city
     *            用户输入的城市名称
     * @return 字符串 用,分割
     */
    public Hashtable<String, Object> getWeather(String city) {
        Hashtable<String, Object> weathers = new Hashtable<String, Object>(0);
        try {
            Document doc = null;
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputStream is = getSoapInputStream(city);
            doc = db.parse(is);
            NodeList nl = doc.getElementsByTagName("string");
            for (int count = 0; count < nl.getLength(); count++) {
                Node n = nl.item(count);
                String nv = n.getFirstChild().getNodeValue();// 当前节点信息
                nv = (nv == null ? "" : nv);
                if (nv.equals("查询结果为空!")) {
                    return null;
                }
                if (count != 11) {
                    weathers.put(WeatherObj.input.get(count), nv);
                    continue;
                }
                if (count == 11) {
                    this.analyzedZhiShu(weathers, nv);
                }
            }
            is.close();

            return weathers;

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

    /**
     * @param weathers
     * @param indexId
     *            解析各个指数信息
     */
    private boolean analyzedZhiShu(Hashtable<String, Object> weathers, String zhiShuMess) {
        if (weathers == null || zhiShuMess == null || zhiShuMess.equals("")) {
            return false;
        }
        ArrayList<WeatherObj> objs = new ArrayList<WeatherObj>(0);

        String s1Content = "";
        String s2Content = "";
        String s3Content = "";
        String s4Content = "";
        String s5Content = "";
        String s6Content = "";
        String s7Content = "";
        String s8Content = "";
        String s9Content = "";
        String s10Content = "";
        // 这里开始进行具体详细测试
        String str = zhiShuMess;
        // 穿衣指数
        s1Content = str.substring(str.indexOf(WeatherObj.CHUANYIZHISHU)+ WeatherObj.CHUANYIZHISHU.length(), str.indexOf(WeatherObj.GANMAOZHISHU));
        WeatherObj obj1 = new WeatherObj();
        obj1.setName(WeatherObj.CHUANYIZHISHU);
        obj1.setMessage(s1Content);
        objs.add(obj1);
        // 感冒指数
        s2Content = str.substring(str.indexOf(WeatherObj.GANMAOZHISHU)+ WeatherObj.GANMAOZHISHU.length(), str.indexOf(WeatherObj.YUNDONGZHISHU));
        WeatherObj obj2 = new WeatherObj();
        obj2.setName(WeatherObj.GANMAOZHISHU);
        obj2.setMessage(s2Content);
        objs.add(obj2);
        // 运动指数
        s3Content = str.substring(str.indexOf(WeatherObj.YUNDONGZHISHU)+ WeatherObj.YUNDONGZHISHU.length(), str.indexOf(WeatherObj.XICHEZHISHU));
        WeatherObj obj3 = new WeatherObj();
        obj3.setName(WeatherObj.YUNDONGZHISHU);
        obj3.setMessage(s3Content);
        objs.add(obj3);
        // 洗车指数
        s4Content = str.substring(str.indexOf(WeatherObj.XICHEZHISHU)+ WeatherObj.XICHEZHISHU.length(), str.indexOf(WeatherObj.LIANGSHAIZHISHU));
        WeatherObj obj4 = new WeatherObj();
        obj4.setName(WeatherObj.XICHEZHISHU);
        obj4.setMessage(s4Content);
        objs.add(obj4);
        // 晾晒指数
        s5Content = str.substring(str.indexOf(WeatherObj.LIANGSHAIZHISHU)+ WeatherObj.LIANGSHAIZHISHU.length(), str.indexOf(WeatherObj.LVYOUZHISHU));
        WeatherObj obj5 = new WeatherObj();
        obj5.setName(WeatherObj.LIANGSHAIZHISHU);
        obj5.setMessage(s5Content);
        objs.add(obj5);
        // 旅游指数
        s6Content = str.substring(str.indexOf(WeatherObj.LVYOUZHISHU)+ WeatherObj.LVYOUZHISHU.length(), str.indexOf(WeatherObj.LUKUANGZHISHU));
        WeatherObj obj6 = new WeatherObj();
        obj6.setName(WeatherObj.LVYOUZHISHU);
        obj6.setMessage(s6Content);
        objs.add(obj6);
        // 路况指数
        s7Content = str.substring(str.indexOf(WeatherObj.LUKUANGZHISHU)+ WeatherObj.LUKUANGZHISHU.length(), str.indexOf(WeatherObj.SHUSHIDUZHISHU));
        WeatherObj obj7 = new WeatherObj();
        obj7.setName(WeatherObj.LUKUANGZHISHU);
        obj7.setMessage(s7Content);
        objs.add(obj7);
        // 舒适度指数
        s8Content = str.substring(str.indexOf(WeatherObj.SHUSHIDUZHISHU)+ WeatherObj.SHUSHIDUZHISHU.length());
        WeatherObj obj8 = new WeatherObj();
        obj8.setName(WeatherObj.SHUSHIDUZHISHU);
        obj8.setMessage(s8Content);
        objs.add(obj8);
//        // 空气污染指数
//        s8Content = str.substring(str.indexOf(WeatherObj.KONGQIWURANZHISHU)+ WeatherObj.KONGQIWURANZHISHU.length(),str.indexOf(WeatherObj.ZIWAIXIANZHISHU));
//        WeatherObj obj9 = new WeatherObj();
//        obj9.setName(WeatherObj.KONGQIWURANZHISHU);
//        obj9.setMessage(s9Content);
//        objs.add(obj9);
//        // 紫外线指数
//        s8Content = str.substring(str.indexOf(WeatherObj.ZIWAIXIANZHISHU)+ WeatherObj.ZIWAIXIANZHISHU.length());
//        WeatherObj obj10 = new WeatherObj();
//        obj10.setName(WeatherObj.ZIWAIXIANZHISHU);
//        obj10.setMessage(s10Content);
//        objs.add(obj10);

        weathers.put(WeatherObj.ZHISHU, objs);
        return true;
    }
}

3、创建一个jsp页面,展示天气预报,代码如下:

    <%@ page language="java" pageEncoding="GBK"%>  
    <%@ page import="java.util.ArrayList,java.util.Hashtable"%>  
    <jsp:directive.page import="com.hnwater.business.weather.WeatherObj;"/>  
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    <html>  
        <head>  
            <title>城市天气信息</title>  
    <%--       
        <link rel="stylesheet" type="text/css" href="../css/webstyle.css">  
    --%>  
        </head>  
    <style>  
    body{  
        font-size:12px;  
    }  
    table{  
        border-collapse:sparate;  
        border-spacing:0px;  
    }  
    td{  
        padding:0px;  
        border:0px solid #000;  
        text-align:center;  
        font-size:12px;  
        color:#2A5CAA;  
        border-color:#2A5CAA;  
    }  
    .noMess{  
        text-align: center;  
        text-valign: center;  
    } 
    </style>    
        <body>  
    <%  
        String city = "桂林";  
        Hashtable<String,Object> weathers = com.hnwater.business.weather.WeatherUtil  
            .getInstance().getWeather(city);  
        if(weathers == null){                     
    %>  
        <span class="noMess">  
            暂不支持该<%=city%>地区天气预报!!!  
        </span>     
    <%}else{ %>  
        <table border="0" cellpadding="0" cellspacing="0" width="380">  
            <tr>  
                <td><%=weathers.get(WeatherObj.REGIONFIRST) + " " + weathers.get(WeatherObj.REGIONSECOND)%> 72小时天气预报</td>  
                <td>最新上报时间:<%=weathers.get(WeatherObj.REPORTTIME)%></td>  
            </tr>  
            <tr>  
                <td colspan="2">  
                    <table border="0" cellpadding="0" cellspacing="0">  
                    <tr>  
                        <td><%=weathers.get(WeatherObj.TODAYDATE) + " " + weathers.get(WeatherObj.TODAYTEMPERATURE)%></td>  
                    </tr>  
                    <tr>  
                        <td><%=weathers.get(WeatherObj.TODAYWIND)%></td>  
                    </tr>  
                    <tr>  
                        <td>  
                            <img src="../images/weather/<%=weathers.get(WeatherObj.TODAYPIC_1)%>">  
                            &nbsp;  
                            <img src="../images/weather/<%=weathers.get(WeatherObj.TODAYPIC_2)%>">  
                        </td>  
                    </tr>  
                    <tr>  
                        <td><%=weathers.get(WeatherObj.TODAYDETAIL)%></td>  
                    </tr>  
                    </table>  
                </td>  
            </tr>  
            <tr>  
                <td colspan="2">  
                    <table border="0" cellpadding="0" cellspacing="0">  
                    <tr>  
                        <td><%=weathers.get(WeatherObj.TOMORROWDATE) + " " + weathers.get(WeatherObj.TOMORROWTEMPERATURE)%></td>  
                    </tr>  
                    <tr>  
                        <td><%=weathers.get(WeatherObj.TOMORROWWIND)%></td>  
                    </tr>  
                    <tr>  
                        <td>  
                            <img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_1)%>">  
                            &nbsp;  
                            <img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_2)%>">  
                        </td>  
                    </tr>  
                    </table>  
                </td>  
            </tr>  
            <tr>  
                <td colspan="2">  
                    <table border="0" cellpadding="0" cellspacing="0">  
                    <tr>  
                        <td><%=weathers.get(WeatherObj.TOMORROWDATE) + " " + weathers.get(WeatherObj.TOMORROWTEMPERATURE)%></td>  
                    </tr>  
                    <tr>  
                        <td><%=weathers.get(WeatherObj.TOMORROWWIND)%></td>  
                    </tr>  
                    <tr>  
                        <td>  
                            <img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_1)%>">  
                            &nbsp;  
                            <img src="../images/weather/<%=weathers.get(WeatherObj.TOMORROWPIC_2)%>">  
                        </td>  
                    </tr>  
                    </table>  
                </td>  
            </tr>  
            <%  
                ArrayList<WeatherObj> objs = (ArrayList<WeatherObj>)weathers.get(WeatherObj.ZHISHU);  
                for(int i = 0;objs != null && i < objs.size();i++){  
                    WeatherObj obj = objs.get(i);  
             %>  
            <tr>  
                <td><%=obj.getName()%></td>  
                <td><%=obj.getMessage()%></td>  
            </tr>  
            <%} %>  
        </table> 
    <%} %>          
        </body>  
    </html> 


要用Java实现天气预报功能,你需要准备以下内容: 1. 天气API:你需要从第三方天气服务商获取天气数据,例如心知天气、和风天气等。这些服务商一般都会提供API接口,方便你获取天气数据。 2. Java HTTP客户端:你需要用Java编写HTTP客户端,向天气API发送请求,并接收响应数据。 3. JSON解析库:获取到的天气数据一般是JSON格式的,你需要用Java的JSON解析库,将JSON数据解析为Java对象。 4. 用户界面:你需要用Java Swing或JavaFX等UI库,创建一个用户界面,方便用户输入城市名,显示天气数据等。 下面是一个简单Java天气预报示例代码,仅供参考: ```java import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import org.json.JSONArray; import org.json.JSONObject; public class WeatherApp extends JFrame implements ActionListener { private JTextField cityField; private JLabel weatherLabel; public WeatherApp() { super("天气预报"); setSize(400, 200); JPanel panel = new JPanel(); panel.setLayout(new BorderLayout()); cityField = new JTextField(); panel.add(cityField, BorderLayout.CENTER); JButton button = new JButton("查询"); button.addActionListener(this); panel.add(button, BorderLayout.EAST); weatherLabel = new JLabel(); panel.add(weatherLabel, BorderLayout.SOUTH); add(panel); setVisible(true); } public static void main(String[] args) { new WeatherApp(); } @Override public void actionPerformed(ActionEvent e) { try { String city = cityField.getText(); String urlStr = "https://api.seniverse.com/v3/weather/now.json?key=your_key&location=" + city; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } reader.close(); conn.disconnect(); JSONObject json = new JSONObject(sb.toString()); JSONArray results = json.getJSONArray("results"); JSONObject result = results.getJSONObject(0); JSONObject now = result.getJSONObject("now"); String text = now.getString("text"); String temperature = now.getString("temperature"); String weather = String.format("%s,温度:%s℃", text, temperature); weatherLabel.setText(weather); } catch (Exception ex) { weatherLabel.setText("查询失败:" + ex.getMessage()); ex.printStackTrace(); } } } ``` 上述示例代码使用了心知天气的API接口。你需要将代码中的`your_key`替换为你的API密钥,才能正常使用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值