文档章节

天气插件

刘胜球
 刘胜球
发布于 2013/12/25 14:39
字数 1901
阅读 258
收藏 1
  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  城市与城市代码的对应

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

© 著作权归作者所有

共有 人打赏支持
刘胜球
粉丝 8
博文 53
码字总数 78790
作品 0
常德
后端工程师
Android:一个非常非常简单的天气app

界面截图: 界面非常的简单。。。 数据来源Openweathermap和和风天气。 主要界面使用RecyclerView 在新版的RecyclerView里面,里面的item布局android:layoutheight不可以为matchparent,应为...

absolve
2016/08/05
237
0
Franky/WeatherMap

地级行政区天气组件,基于高德地图 JavaScript API V1.3 使用方法: 引入插件样式文件 引入高德地图JavaScript API文件 引入weather-amap.j...

Franky
2014/09/19
0
0
全球主要城市实时天气查询

作为学习javascript的练习,我制作了一个网页,可以查询全球主要城市此时此刻的天气,请点击进入。 写这个网页,主要是为了学习,如何在同一个页面中打开一个新窗口。这种技术的英文名字叫做...

阮一峰
2007/12/20
0
0
给开发者准备的 10 款最好的 jQuery 日历插件

这篇文章介绍的是 10 款最棒而且又很有用的 jQuery日历插件,允许开发者们把这些漂亮的日历插件结合到自己的网站中。这些日历插件易用性都很强,轻轻松松的就可以把漂亮的日历插件装饰到你的...

oschina
2014/01/27
47.1K
10
网页天气预报--jQuery天气预报插件

这是一个开源的、基于jQuery 函数库的 JavaScript 天气预报脚本插件。 代码语法完全符合W3C网页标准,完全兼容各种主流浏览器。 本插件主要用于天气预报的展示。 jQuery weather v3.0.0( 201...

网页天气预报
2013/04/09
9.5K
2

没有更多内容

加载失败,请刷新页面

加载更多

使用Newtonsoft将DataTable转Json

使用Newtonsoft将DataTable转Json Newtonsoft提供的将DataTable转成Json: /// <summary> /// DataTable转Json /// </summary> /// <param name="dt"></param> /// <ret......

DemonsI
16分钟前
1
0
centos7安装zookeeper3.4.6

注:zookeeper充当注册中心 下载地址 http://mirror.bit.edu.cn/apache/zookeeper/zookeeper-3.4.6/ 单机 下载完成后,将安装包上传值服务器,解压 tar xvzf zookeeper-3.4.6.tar.gz 进入解...

码代码的小司机
17分钟前
1
0
136. Single Number

136. Single Number 题意:一个数组中所有数字都是两两相同,只有一个数字是单独的,求出这个数字的值。 很简单的题,使用异或就能处理。 异或介绍:bit位上的值不同,异或后,值为1.否则为0...

117
19分钟前
1
0
Hash和HashCode深入理解

目录介绍 1.Hash的作用介绍 1.1 Hash的定义 1.2 Hash函数特性 1.3 Hash的使用场景 2.如何判断两个对象相等 2.1 判断两个字符串 2.2 判断两个int数值 2.3 其他基本类型 3.HashCode深入分析 3....

潇湘剑雨
25分钟前
1
0
ecshop 漏洞如何修复 补丁升级与安全修复详情

目前ecshop漏洞大面积爆发,包括最新版的ecshop 3.0,ecshop 4.0,ecshop2.7.3全系列版本都存在着高危网站漏洞,导致网站被黑,被篡改,被挂马,许多商城系统深受其漏洞的攻击,给商城的运营者...

网站安全
25分钟前
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部