`
starbhhc
  • 浏览: 655222 次
  • 性别: Icon_minigender_2
  • 来自: 深圳
社区版块
存档分类
最新评论

java获取5日天气预报(json数据)

阅读更多
地区代码整理在附件中citys.xml
说明:p代表省 n 省名称例如:B 北京,c 城市

返回的json数据示例:

Java 代码
{"weatherinfo":{"city":"上海","city_en":"shanghai","date_y":"2010年5月31日","date":"庚寅年四月十八","week":"星期一","fchh":"08","cityid":"101020100","temp1":"27℃~18℃","temp2":"26℃~18℃","temp3":"27℃~19℃","temp4":"27℃~20℃","temp5":"25℃~20℃","tempF1":"80.6℉~64.4℉","tempF2":"78.8℉~64.4℉","tempF3":"80.6℉~66.2℉","tempF4":"80.6℉~68℉","tempF5":"77℉~68℉","weather1":"多云","weather2":"多云","weather3":"晴转多云","weather4":"多云","weather5":"阴","img1":"1","img2":"99","img3":"1","img4":"99","img5":"0","img6":"1","img7":"1","img8":"99","img9":"2","img10":"99","img_single":"1","img_title1":"多云","img_title2":"多云","img_title3":"多云","img_title4":"多云","img_title5":"晴","img_title6":"多云","img_title7":"多云","img_title8":"多云","img_title9":"阴","img_title10":"阴","img_title_single":"多云","wind1":"东风3-4级","wind2":"东风3-4级","wind3":"东风3-4级","wind4":"东南风4-5级","wind5":"东南风转东风4-5级","fx1":"东风","fx2":"东风","fl1":"3-4级","fl2":"3-4级","fl3":"3-4级","fl4":"4-5级","fl5":"4-5级","index":"暂缺","index_d":"暂缺","index48":"暂缺","index48_d":"暂缺","index_uv":"弱","index48_uv":"弱","index_xc":"适宜","index_tr":"很适宜","index_co":"较舒适","st1":"26","st2":"17","st3":"25","st4":"17","st5":"25","st6":"18"}}
{"weatherinfo":{"city":"上海","city_en":"shanghai","date_y":"2010年5月31日","date":"庚寅年四月十八","week":"星期一","fchh":"08","cityid":"101020100","temp1":"27℃~18℃","temp2":"26℃~18℃","temp3":"27℃~19℃","temp4":"27℃~20℃","temp5":"25℃~20℃","tempF1":"80.6℉~64.4℉","tempF2":"78.8℉~64.4℉","tempF3":"80.6℉~66.2℉","tempF4":"80.6℉~68℉","tempF5":"77℉~68℉","weather1":"多云","weather2":"多云","weather3":"晴转多云","weather4":"多云","weather5":"阴","img1":"1","img2":"99","img3":"1","img4":"99","img5":"0","img6":"1","img7":"1","img8":"99","img9":"2","img10":"99","img_single":"1","img_title1":"多云","img_title2":"多云","img_title3":"多云","img_title4":"多云","img_title5":"晴","img_title6":"多云","img_title7":"多云","img_title8":"多云","img_title9":"阴","img_title10":"阴","img_title_single":"多云","wind1":"东风3-4级","wind2":"东风3-4级","wind3":"东风3-4级","wind4":"东南风4-5级","wind5":"东南风转东风4-5级","fx1":"东风","fx2":"东风","fl1":"3-4级","fl2":"3-4级","fl3":"3-4级","fl4":"4-5级","fl5":"4-5级","index":"暂缺","index_d":"暂缺","index48":"暂缺","index48_d":"暂缺","index_uv":"弱","index48_uv":"弱","index_xc":"适宜","index_tr":"很适宜","index_co":"较舒适","st1":"26","st2":"17","st3":"25","st4":"17","st5":"25","st6":"18"}}


导航189天气抓取示例:
Crawler.java

Java 代码
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
import org.htmlparser.lexer.Lexer;

public abstract class Crawler extends TimerTask {
     
    public String convert2String(String html) {
        if (html != null) {
            String str = html;
            Lexer l = new Lexer(str);
            Parser parser = new Parser(l);
            StringBean sb = new StringBean();
            try {
                parser.visitAllNodesWith(sb);
            } catch (Exception e) {
                return str;
            }
            String ret = sb.getStrings();
            if (ret != null) {
                ret = ret.replace("\r", "");
                ret = ret.replace("\t", "");
            }
            return ret;
        }
        return "";
    }

    public String formatString(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        str = convert2String(str);
        str = str.replaceAll("&", "&");
        str = str.replaceAll("\"", "“").replaceAll("<", "").replaceAll("\"", "“");
        str = str.trim();
        return str;
    }

}
import java.util.TimerTask;

import org.apache.commons.lang.StringUtils;
import org.htmlparser.Parser;
import org.htmlparser.beans.StringBean;
import org.htmlparser.lexer.Lexer;

public abstract class Crawler extends TimerTask {
   
    public String convert2String(String html) {
        if (html != null) {
            String str = html;
            Lexer l = new Lexer(str);
            Parser parser = new Parser(l);
            StringBean sb = new StringBean();
            try {
                parser.visitAllNodesWith(sb);
            } catch (Exception e) {
                return str;
            }
            String ret = sb.getStrings();
            if (ret != null) {
                ret = ret.replace("\r", "");
                ret = ret.replace("\t", "");
            }
            return ret;
        }
        return "";
    }

    public String formatString(String str) {
        if (StringUtils.isBlank(str)) {
            return "";
        }
        str = convert2String(str);
        str = str.replaceAll("&", "&amp;");
        str = str.replaceAll("\"", "“").replaceAll("<", "").replaceAll("\"", "“");
        str = str.trim();
        return str;
    }

}


WeatherCrawler.java

Java 代码
import java.net.URI;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.dh189.util.Constants;
import com.dh189.util.Util;

public class WeatherCrawler extends Crawler {

    private static final String GETURL = "http://m.weather.com.cn/data/";

    DefaultHttpClient httpclient = new DefaultHttpClient();

    public void start() {
        String[] citys = Constants.WEATHERCITYCODE.split(",");
        for (String city : citys) {
            String url = GETURL + city + ".html";
            String val = getWeather(url);
            try {
                JSONObject json = new JSONObject(val);
                JSONObject j = json.getJSONObject("weatherinfo");
                String alt1 = j.getString("weather1") + "&nbsp;" + j.getString("wind1");
                String alt2 = j.getString("weather2") + "&nbsp;" + j.getString("wind2");
                String html = "<div class=\"w_l\"> <div class=\"w_l_u\"> <table style=\"width: 35px;height: 45px;\"> <tr> <td style=\"color: #F24F00\"><b>"
                        + j.getString("city")
                        + "</b></td> </tr> </table> < /div> <div class=\"w_l_d\"><a href=\"javascript:dingCity(); \" title=\"定制天气预报\" target=\"_self\">定制</a> </div> < /div> <ul> <li class=\"w_r\" style=\"width: 222px;\"> <table style=\"height: 70px;width: 100%;float: left;\"> <tr valign=\"bottom\"> <td><img src=\"images/weather/b"
                        + j.getString("img1") + ".gif\" height=\"30\"/></td> <td><img src=\"images/weather/b" + j.getString("img3")
                        + ".gif\" height=\"30\"/></td> </tr> <tr> <td width=\"105\" style=\"line-height: 15px;\"><a href=\"http://www.weather.com.cn/html/weather/" + city + ".shtml\" title=\""
                        + alt1 + "\">" + Util.getWeekOfDate(new Date()) + ":" + j.getString("temp1") + "<br/>" + j.getString("weather1")
                        + "</a></td> <td width=\"105\" style=\"line-height: 15px;\"><a href=\"http://www.weather.com.cn/html/weather/" + city + ".shtml\" title=\"" + alt2 + "\">"
                        + Util.getWeekOfDate(Util.dateAddOrReduce(new Date(), 1)) + ":" + j.getString("temp2") + "<br/>" + j.getString("weather2") + "</a></td></tr></table></li></ul>";
                String dir = Constants.WEATHERDIR + city + ".html";
                Util.writeSortFile(dir, html, false);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理GET请求,返回整个页面
     *
     * @param url
     * @return
     */
    public String getWeather(String url) {
        String content = null;
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 30 * 1000);
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), 30 * 1000);
            //伪装成火狐浏览器
            HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9");
            HttpGet httpget = new HttpGet();
            content = "";
            httpget.setURI(new URI(url));
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            content = null;
            if (entity != null) {
                content = EntityUtils.toString(entity);
                httpget.abort();
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    @Override
    public void run() {
        start();
    }
}
import java.net.URI;
import java.util.Date;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.dh189.util.Constants;
import com.dh189.util.Util;

public class WeatherCrawler extends Crawler {

    private static final String GETURL = "http://m.weather.com.cn/data/";

    DefaultHttpClient httpclient = new DefaultHttpClient();

    public void start() {
        String[] citys = Constants.WEATHERCITYCODE.split(",");
        for (String city : citys) {
            String url = GETURL + city + ".html";
            String val = getWeather(url);
            try {
                JSONObject json = new JSONObject(val);
                JSONObject j = json.getJSONObject("weatherinfo");
                String alt1 = j.getString("weather1") + "&nbsp;" + j.getString("wind1");
                String alt2 = j.getString("weather2") + "&nbsp;" + j.getString("wind2");
                String html = "<div class=\"w_l\"> <div class=\"w_l_u\"> <table style=\"width: 35px;height: 45px;\"> <tr> <td style=\"color: #F24F00\"><b>"
                        + j.getString("city")
                        + "</b></td> </tr> </table> </div> <div class=\"w_l_d\"><a href=\"javascript:dingCity();\" title=\"定制天气预报\" target=\"_self\">定制</a> </div> </div> <ul> <li class=\"w_r\" style=\"width: 222px;\"> <table style=\"height: 70px;width: 100%;float: left;\"> <tr valign=\"bottom\"> <td><img src=\"images/weather/b"
                        + j.getString("img1") + ".gif\" height=\"30\"/></td> <td><img src=\"images/weather/b" + j.getString("img3")
                        + ".gif\" height=\"30\"/></td> </tr> <tr> <td width=\"105\" style=\"line-height: 15px;\"><a href=\"http://www.weather.com.cn/html/weather/" + city + ".shtml\" title=\""
                        + alt1 + "\">" + Util.getWeekOfDate(new Date()) + ":" + j.getString("temp1") + "<br/>" + j.getString("weather1")
                        + "</a></td> <td width=\"105\" style=\"line-height: 15px;\"><a href=\"http://www.weather.com.cn/html/weather/" + city + ".shtml\" title=\"" + alt2 + "\">"
                        + Util.getWeekOfDate(Util.dateAddOrReduce(new Date(), 1)) + ":" + j.getString("temp2") + "<br/>" + j.getString("weather2") + "</a></td></tr></table></li></ul>";
                String dir = Constants.WEATHERDIR + city + ".html";
                Util.writeSortFile(dir, html, false);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理GET请求,返回整个页面
     *
     * @param url
     * @return
     */
    public String getWeather(String url) {
        String content = null;
        try {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 30 * 1000);
            HttpConnectionParams.setSoTimeout(httpclient.getParams(), 30 * 1000);
            //伪装成火狐浏览器
            HttpProtocolParams.setUserAgent(httpclient.getParams(), "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9");
            HttpGet httpget = new HttpGet();
            content = "";
            httpget.setURI(new URI(url));
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            content = null;
            if (entity != null) {
                content = EntityUtils.toString(entity);
                httpget.abort();
                httpclient.getConnectionManager().shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    @Override
    public void run() {
        start();
    }
}
分享到:
评论

相关推荐

    天气预报json解析

    标题中的“天气预报json解析”指的是在编程领域中,如何处理和解析来自网络的天气预报数据,这些数据通常以JSON(JavaScript Object Notation)格式提供。JSON是一种轻量级的数据交换格式,因其易于人阅读和编写,...

    天气预报的源代码

    3. **JSON解析**:天气API通常返回JSON格式的数据,需要使用如Gson或Jackson这样的库来解析和转换成Java对象。 4. **Android布局设计**:XML布局文件用于定义用户界面,包括各种控件如TextView(显示天气信息)、...

    基于Android的天气预报APP的开发.docx

    3. **GSON**: Google 提供的一款 Java 库,用于 JSON 数据格式的序列化与反序列化。本项目中,GSON 被用来解析服务器返回的天气数据,将其转换为可操作的对象形式。 #### 三、主要功能模块 1. **启动程序模块**:...

    毕业设计-集天气预报、星座运势、老黄历.zip

    该项目“毕业设计-集天气预报、星座运势、老黄历.zip”是一个综合性的应用程序,旨在提供用户日常生活中可能需要的多种信息查询服务。主要包含三个功能模块:天气预报、星座运势和老黄历。让我们详细了解一下这些...

    安卓天气日历时间选择倒计时相关-日期倒计时倒数日计算两个日期之间的天数.zip

    此类应用可以帮助用户方便地查看天气预报、管理日程,并设置重要的日期提醒。在这个名为“安卓天气日历时间选择倒计时相关-日期倒计时倒数日计算两个日期之间的天数.zip”的压缩包中,包含了一些相关的代码资源和...

    weatherDemo1128_可用

    【标签】"weatherDemo"进一步证实了这是一个关于天气的演示程序,可能是用来展示如何获取和处理天气数据、展示天气预报或者进行气候分析的代码实例。 【压缩包子文件的文件名称列表】中,"weatherDemo1128_可用.rar...

    2021031406_基于安卓的航班及天气查询系统手机app.rar

    【标题】中的“2021031406_基于安卓的航班及天气查询系统手机app”表明这是一个在2021年3月14日开发的Android应用程序,专注于提供航班查询和天气预报服务。这样的应用通常涉及到移动开发、Android SDK、网络请求...

    weather:天气app

    - 解析JSON数据,将结果转化为Java对象。 2. 展示天气信息: - 设计UI界面,使用XML布局文件创建各个组件,如TextView显示温度、ImageView展示天气图标。 - 在Activity或Fragment中绑定UI组件,将获取到的天气...

    2014030402011-杜敏1

    3. **天气预报**:欧酷天气模块提供准确的天气信息,帮助用户做好出行安排。 4. **智能对话**:采用图灵机器人技术,实现了与用户的自然语言交互,增强用户体验。 5. **个人信息展示**:展示作者的相关信息,增加...

    apixu-android:适用于Apixu Weather API的Android库

    2. **天气预报(Forecasts)**: 获取未来几天的天气预报,可以按小时或日进行查询。 3. **历史天气(Historical Data)**: 查询过去特定日期的天气数据,对于数据分析或研究很有用。 4. **地点搜索(Location Search...

    制作万年历 日期 农历 温度显示 定时 功能

    - 温度显示通常需要接入天气API,如OpenWeatherMap、AccuWeather等,获取实时或预报温度数据。需要处理网络请求,JSON或其他数据格式解析,并将结果显示在界面上。 - 如果设备支持硬件传感器,如智能家居系统,还...

    Weather-App

    常见的天气API有OpenWeatherMap、AccuWeather等,它们提供JSON或XML格式的天气预报数据。开发者需要编写代码来请求这些API,解析返回的数据,并将其存储在本地或云端数据库。 2. **数据处理**:获取的原始数据需要...

    Sunshine:为Udacity Android课程开发的Android Weather App

    "Sunshine"是一款专为Udacity Android课程开发的天气应用程序,它提供了一个直观的界面,让用户能够轻松查看天气预报。这款应用展示了Android平台上的基本功能和设计原则,包括数据获取、用户界面设计以及设备适应性...

    Sun-Shine-App:优达学城安卓课程

    5. **JSON解析**:将获取的天气数据解析成Java对象,如使用Gson或Jackson库。 6. **Android权限**:理解和处理AndroidManifest.xml中的权限声明,如访问网络或读写外部存储。 7. **UI更新**:掌握如何在主线程和工作...

    Sunshine-Enhanced

    【描述】描述中提到的"阳光"可能是指这个应用的主题或功能,它可能是一个天气预报应用,展示阳光明媚的日子或者提供有关日照时间、紫外线指数等与阳光相关的数据。Sunshine是Udacity课程的一个实践项目,学员通过...

Global site tag (gtag.js) - Google Analytics