天气插件
天气插件
刘胜球 发表于4年前
天气插件
  • 发表于 4年前
  • 阅读 252
  • 收藏 1
  • 点赞 0
  • 评论 0

新睿云服务器60天免费使用,快来体验!>>>   

摘要: 从中国天气网API(例 http://m.weather.com.cn/data/101050101.html )得到JSON格式的字符串,解析该字符串,得到天气数据,并按特定的方式显示。
  1. 从中国天气网API得到天气数据并解析

public class WeatherDate {
    private String cityId;
    private URLConnection connectionData;
    private StringBuilder sb;
    private BufferedReader br;// 读取data数据流
    private JSONObject jsonData;
    private JSONObject info;

    public WeatherDate(String cityId) {
        // 解析本机ip地址
        this.cityId = cityId;
    }

    /**
     *
      * getDate(从气象台得到天气数据)
      * @return
      * @throws IOException
     */
    public List<Map<String, Object>> getDate() throws IOException{
        // 连接中央气象台的API
        URL url = new URL("http://m.weather.com.cn/data/" + cityId + ".html");
        connectionData = url.openConnection();

        //设置代理服务器,有必要设置时才设置
        System.getProperties().put("proxySet", "true");
        System.getProperties().put("proxyHost", "10.123.74.137");
        System.getProperties().put("proxyPort", "808");
        connectionData.setConnectTimeout(3000);
        try {
            br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
            sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null)
                sb.append(line);
        } catch (SocketTimeoutException e) {
            System.out.println("连接超时");
        } catch (FileNotFoundException e) {
            System.out.println("加载文件出错");
        } catch (UnknownHostException e){
            System.out.println("网络异常");
        }
        String datas = sb.toString();

        jsonData = JSONObject.fromObject(datas);
        info = jsonData.getJSONObject("weatherinfo");

        // 得到今明两天的天气情况
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (int i = 1; i <= 2; i++) {
            // 得到今明两天的日期
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.DAY_OF_YEAR, i - 1);
            Date date = cal.getTime();
            SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");

            Map<String, Object> map = new HashMap<String, Object>();
            if(cityId.equals("101010300"))
                map.put("city", "朝阳区");
            if(cityId.equals("101010600"))
                map.put("city", "通州区");
            else
                map.put("city", info.getString("city").toString());// 城市
            map.put("date_y", sf.format(date));// 日期
            map.put("week", getWeek(cal.get(Calendar.DAY_OF_WEEK)));// 星期
            map.put("fchh", info.getString("fchh").toString());// 发布时间
            map.put("weather", info.getString("weather" + i).toString());// 天气
            map.put("day_img", info.getString("img"+(2*i-1)).toString());//白天天气图片
            map.put("night_img", info.getString("img"+2*i).toString());//晚上天气图片
            map.put("temp", info.getString("temp" + i).toString());// 温度
            map.put("wind", info.getString("wind" + i).toString());// 风况
            map.put("fl", info.getString("fl" + i).toString());// 风速
            map.put("index_uv", info.getString("index_uv").toString());// 紫外指数
            list.add(map);
        }
        return list;
    }
   
    /**
     *
      * getImageIn(从气象台得到天气图片输入流)
      * @param urlName
      * @return
      * @throws IOException
     */
    public InputStream getImageIn(String urlName) throws IOException{
        InputStream in=null;
        URL url = new URL(urlName);
        connectionData = url.openConnection();
        System.getProperties().put("proxySet", "true");
        System.getProperties().put("proxyHost", "10.123.74.137");
        System.getProperties().put("proxyPort", "808");
        connectionData.setConnectTimeout(3000);
        try{
            in=connectionData.getInputStream();
        }catch (UnknownHostException e) {
            System.out.println("网络异常");
        }
        return in;
    }
   
    /**
     *
      * getWeek(得到星期)
      * @param iw
      * @return
     */
    private String getWeek(int iw) {
        String weekStr = "";
        switch (iw) {
        case 1:
            weekStr = "星期天";
            break;
        case 2:
            weekStr = "星期一";
            break;
        case 3:
            weekStr = "星期二";
            break;
        case 4:
            weekStr = "星期三";
            break;
        case 5:
            weekStr = "星期四";
            break;
        case 6:
            weekStr = "星期五";
            break;
        case 7:
            weekStr = "星期六";
            break;
        default:
            break;
        }
        return weekStr;
    }

    public static void main(String[] args) {
        try {
            WeatherDate wd=new WeatherDate("101280101"); // 101280101(广州)就是你的城市代码
            List<Map<String, Object>> list=wd.getDate();
            // 控制台打印出天气
            for (int j = 0; j < list.size(); j++) {
                Map<String, Object> wMap = list.get(j);
                System.out.println(wMap.get("city") + "\t" + wMap.get("date_y") + "\t" + wMap.get("week") + "\t" + wMap.get("weather") + "\t"
                        + wMap.get("temp") + "\t" + wMap.get("index_uv")+"\t"+wMap.get("day_img")+"\t"+wMap.get("night_img"));
            }
      
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

2. 显示今明两天天气状况

public class ApgWeatherShow extends Composite {
    private WeatherDate weatherDate;
    private String cityId;
    private List<Map<String, Object>> list;
    private Button button;
   

    /**
     * 创建一个新的实例
     * @param parent
     * @param style
     * @param cityId
     * @throws Exception
     */
    public ApgWeatherShow(Composite parent, int style, String cityId) throws Exception {
        super(parent, style);
        this.cityId = cityId;
        this.setSize(500, 200);

        weatherDate = new WeatherDate(cityId);
        list = weatherDate.getDate();

        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> wMap = list.get(i);
            Label label1 = new Label(this, style);
            label1.setText(wMap.get("date_y").toString().substring(5) + " " + wMap.get("week").toString());
            label1.setBounds(0 + i * 220, 0, 100, 20);

            if (i == 0) {
                final Label label2 = new Label(this, style);
                label2.setText(wMap.get("city").toString());
                label2.setBounds(0, 20, 85, 20);

                button= new Button(this, style);
                button.setText("更换");
                button.setBounds(0, 40, 40, 20);
                button.addSelectionListener(new SelectionAdapter() {

                    @Override
                    public void widgetSelected(SelectionEvent e) {
                        WeatherView weatherView=new WeatherView();
                        if(weatherView.getWeatherShow()!=null)
                            weatherView.getWeatherShow().setVisible(false);
                       
                        new ApgCityShow(getParent(), getStyle(), label2.getText());
                        if(ApgCityShow.getAws()!=null)
                            ApgCityShow.getAws().setVisible(false);
                    }
                });
            }

            Label label3 = new Label(this, style);
            label3.setImage(new Image(this.getDisplay(), weatherDate.getImageIn(getUrlName("day_img", wMap))));
            label3.setBounds(100 + i * 220, 0, 30, 20);
            Label label4 = new Label(this, style);
            label4.setImage(new Image(this.getDisplay(), weatherDate.getImageIn(getUrlName("night_img", wMap))));
            label4.setBounds(100 + i * 220, 40, 30, 20);

            Label label5 = new Label(this, style);
            label5.setText(wMap.get("weather").toString());
            label5.setBounds(140 + i * 220, 0, 75, 20);

            Label label6 = new Label(this, style);
            label6.setText(wMap.get("temp").toString());
            label6.setBounds(140 + i * 220, 40, 75, 20);
        }
    }

    /**
     *
      * getUrlName(得到天气图片url地址)
      * @param imgName
      * @return
      * @throws IOException
     */
    public String getUrlName(String imgName, Map<String, Object> map) throws IOException {
        String urlName = "";
        String imgId = "";
        if (imgName.equals("day_img")) {
            imgId = map.get("day_img").toString();
            urlName = "http://www.weather.com.cn/m/i/weatherpic/29x20/d" + imgId + ".gif";
        } else {
            imgId = map.get("night_img").toString();

            if (Integer.parseInt(imgId) == 99) {
                imgId = map.get("day_img").toString();
            }
            urlName = "http://www.weather.com.cn/m2/i/icon_weather/29x20/n" + imgId + ".gif";

        }

        return urlName;
    }

   
    public String getCityId() {
        return cityId;
    }

    @Override
    protected void checkSubclass() {
    }
}

 

3. 城市选择显示

public class ApgCityShow extends Composite {
    private Document doc =null;
    private static ApgWeatherShow aws;
    /**
      * 创建一个新的实例
      * @param parent
      * @param style
      */
    public ApgCityShow(Composite parent, int style, String countryName) {
        super(parent, style);
        final Combo provinceCombo = new Combo(getParent(), getStyle());
        provinceCombo.setBounds(10, 30, 80, 20);
        final Combo cityCombo = new Combo(getParent(), getStyle());
        cityCombo.setBounds(100, 30, 100, 20);
        final Combo countryCombo = new Combo(getParent(), getStyle());
        countryCombo.setBounds(210, 30, 120, 20);
        try {
            doc = ApgCityShow.initXml(this.getClass().getResourceAsStream("/area.xml"));
        } catch (Exception e2) {
            e2.printStackTrace();
        }
        initShow(countryName, provinceCombo, cityCombo, countryCombo);
       
        provinceCombo.addSelectionListener(new SelectionAdapter() {

            public void widgetSelected(SelectionEvent e) {
                initProvinceSelect(provinceCombo.getText(), cityCombo, countryCombo);
            }
           
        });
       
        cityCombo.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                initCitySelect(cityCombo.getText(), countryCombo);
            }
           
        });
       
        final Button changeBtn = new Button(getParent(), getStyle());
        changeBtn.setBounds(350, 30, 35, 25);
        changeBtn.setText("确定");
        changeBtn.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                Properties pro = null;
                try {
                    pro = initCityPro();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                String coutryId=(String) pro.get(countryCombo.getText());
                provinceCombo.dispose();
                cityCombo.dispose();
                countryCombo.dispose();
                changeBtn.dispose();
                try {
                    aws =new ApgWeatherShow(getParent(), getStyle(), coutryId);
                    aws.setBounds(10, 10, 500, 70);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
    }

    /**
     *
      * initXml(初始化xml文件)
      * @param xmlIn
      * @throws Exception
      * @return Document
     */
    public static Document initXml(InputStream xmlIn) throws Exception {
        // 获取产生DocumentBuilder的工厂
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // 通过这个工厂产生一个DocumentBuilder
        DocumentBuilder db = dbf.newDocumentBuilder();
        // DocumentBuilder就是用来产生Document的
        Document doc = db.parse(xmlIn);
        return doc;
    }

    /**
      * 根据xpath获取某一个节点
      * @param express
      * @param source
      * @return
      */
    public static Node selectSingleNode(String express, Object source) {// 查找节点,并返回第一个符合条件节点
        Node result = null;
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        try {
            result = (Node) xpath.evaluate(express, source, XPathConstants.NODE);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
    * 根据xpath获取符合条件的所有节点
    * @param express
     * @param source
     * @return
     */
    public static NodeList selectNodes(String express, Object source) {// 查找节点,返回符合条件的节点集。
        NodeList result = null;
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        try {
            result = (NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     *
      * initShow(点击更换时,初始化城市三级级联框)
      * @param city
      * @param provinceCombo
      * @param cityCombo
      * @param countryCombo
     */
    public void initShow(String country,Combo provinceCombo,Combo cityCombo,Combo countryCombo){
        Element e=doc.getDocumentElement();
        //设置默认选择的县或区
        Node countryNode=selectSingleNode("//address/province/city/county [@name='"+country+"']", e);
        String countryName=((Element) countryNode).getAttribute("name");
        countryCombo.setText(countryName);
        //设置默认选择的城市
        Node cityNode=countryNode.getParentNode();
        String cityName=((Element) (cityNode)).getAttribute("name");
        cityCombo.setText(cityName);
        //设置默认选择的省份
        Node provinceNode=cityNode.getParentNode();
        String provinceName=((Element)provinceNode).getAttribute("name");
        provinceCombo.setText(provinceName);
        //设置省份
        NodeList provinceNodeList = e.getElementsByTagName("province");
        for (int i = 0; i < provinceNodeList.getLength(); i++) {
            Element ss = (Element) provinceNodeList.item(i);
            provinceCombo.add(ss.getAttribute("name"));
        }
        //设置城市
        NodeList cityNodeList=selectNodes("//address//province [@name='"+provinceName+"']", e).item(0).getChildNodes();
       
        for(int i=1;i<cityNodeList.getLength();i+=2){
            Element ss=(Element)cityNodeList.item(i);
            cityCombo.add(ss.getAttribute("name"));
        }
        //设置县或区
        NodeList countryNodeList=selectNodes("//address/province/city [@name='"+cityName+"']", e).item(0).getChildNodes();
        for(int i=1;i<countryNodeList.getLength();i+=2){
            Element ss=(Element)countryNodeList.item(i);
            countryCombo.add(ss.getAttribute("name"));
        }
       
    }
   
    /**
     *
      * initProvinceSelect(选择不同省份,城市改变,县或区也跟着变)
      * @param province
      * @param cityCombo
      * @param countryCombo
     */
    public void initProvinceSelect(String province,Combo cityCombo,Combo countryCombo){
        Element e=doc.getDocumentElement();
        cityCombo.removeAll();
        countryCombo.removeAll();
        //设置城市
        NodeList cityNodeList=selectNodes("//address//province [@name='"+province+"']", e).item(0).getChildNodes();
        String textCity=((Element)cityNodeList.item(1)).getAttribute("name");
        cityCombo.setText(textCity);
        for(int i=1;i<cityNodeList.getLength();i+=2){
            Element ss=(Element)cityNodeList.item(i);
            cityCombo.add(ss.getAttribute("name"));
        }
        //设置县或区
        NodeList countryNodeList=selectNodes("//address/province/city [@name='"+textCity+"']", e).item(0).getChildNodes();
        //System.out.println(selectNodes("//address/province/city [@name='"+textCity+"']", e).getLength());
        countryCombo.setText(((Element)countryNodeList.item(1)).getAttribute("name"));
        for(int i=1;i<countryNodeList.getLength();i+=2){
            Element ss=(Element)countryNodeList.item(i);
            countryCombo.add(ss.getAttribute("name"));
        }
    }
   
    /**
     *
      * initCitySelect(选择不同的城市,县或区更着改变)
      * @param city
      * @param countryCombo
     */
    public void initCitySelect(String city,Combo countryCombo){
        Element e=doc.getDocumentElement();
        countryCombo.removeAll();
        //设置县或区
        NodeList countryNodeList=selectNodes("//address/province/city [@name='"+city+"']", e).item(0).getChildNodes();
        countryCombo.setText(((Element)countryNodeList.item(1)).getAttribute("name"));
        for(int i=1;i<countryNodeList.getLength();i+=2){
            Element ss=(Element)countryNodeList.item(i);
            countryCombo.add(ss.getAttribute("name"));
        }
    }
 
    /**
     *
      * initCityPro(这里用一句话描述这个方法的作用)
      * @return
      * @throws IOException
     */
    public Properties initCityPro() throws IOException{
        Properties pro=new Properties();
        InputStream in=this.getClass().getResourceAsStream("/city.xml");
        pro.loadFromXML(in);
        return pro;
    }
   
    public static ApgWeatherShow getAws() {
        return aws;
    }
}

 

4. 定义一个视图,把天气情况或城市显示在上面

public class WeatherView extends ViewPart {
    private static ApgWeatherShow weatherShow;
   
    public WeatherView() {
    }

    /*
     * @param parent
     * @see org.eclipse.ui.part.WorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
     */
    @Override
    public void createPartControl(final Composite parent) {    
        try {
            parent.setLayout(null);
            weatherShow=new ApgWeatherShow(parent, SWT.NONE, "101280101");
            weatherShow.setBounds(10, 10, 500, 70);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
     * @see org.eclipse.ui.part.WorkbenchPart#setFocus()
     */
    @Override
    public void setFocus() {
        // TODO Auto-generated method stub

    }

    public ApgWeatherShow getWeatherShow() {
        return weatherShow;
    } 
}

 

5. 除开SWT相关的jar,还要加入一下jar

 

6. 城市以及城市的代码

area.xml 城市

city.xml  城市与城市代码的对应

需要这两个文件的可以联系我

标签: 天气插件
  • 打赏
  • 点赞
  • 收藏
  • 分享
共有 人打赏支持
粉丝 7
博文 52
码字总数 78790
×
刘胜球
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: