【Java】-利用天气查询API实现天气预报小窗体应用程序(一)

来源:互联网 发布:海水无机氮数据 编辑:程序博客网 时间:2024/05/16 00:42

本例使用中国天气网 提供的API 接口

http://www.weather.com.cn/data/cityinfo/101010100.html

使用了json解析库文件 库文件地址为

http://download.csdn.net/detail/u011791947/8371905


下面直接帖上源代码


package com.weather.ui;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;import java.net.MalformedURLException;import java.net.URL;import javax.imageio.ImageIO;import javax.swing.JFrame;import javax.swing.JPanel;import net.sf.json.JSONObject;public class WhetherFrame extends JFrame {/** * @author guodont * @param args * 城市天气预报 *///BufferedImage biBackground ;//背景图片private StringBuilder strBuilder;private String city;private String cityid;private String templ;private String temph;private String weatherdec;public static void main(String[] args) {WhetherFrame whetherfrm = new WhetherFrame();whetherfrm.setVisible(true);whetherfrm.initData() ;whetherfrm.initView() ;}private void initData() {try {URL url = new URL("http://www.weather.com.cn/data/cityinfo/101010100.html") ;/** * url.openStream () 字节流,需转换为缓冲字符流 */BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())) ;//StringBuffer 线程安全 StringBuffer 在单线程较快strBuilder = new StringBuilder() ;String str = null ;while((str = br.readLine()) != null) {strBuilder.append(str) ;}} catch (MalformedURLException e) {e.printStackTrace();}catch (IOException e) {e.printStackTrace();}System.out.println(strBuilder.toString());JSONObject json = JSONObject.fromObject(strBuilder.toString()) ;JSONObject  weather = json.getJSONObject("weatherinfo") ;city = weather.getString("city") ;cityid = weather.getString("cityid") ;templ = weather.getString("temp1") ;temph = weather.getString("temp2") ;weatherdec = weather.getString("weather") ;}private void initView() {MyPanel mainPanel = new MyPanel() ;this.add(mainPanel) ;this.setSize(850, 500);this.setLocation(300, 200);}class MyPanel extends JPanel {@Overridepublic void paint(Graphics g) {super.paint(g);Font f = new Font("Microsoft Yahei",Font.BOLD,32) ;g.setFont(f );g.drawString(city+"天气"+"      "+weatherdec, 100,100);g.setFont(new  Font("Microsoft Yahei",Font.PLAIN,24));g.drawString("最高气温"+temph, 100,150);g.drawString("最低气温"+templ, 100,180);}}}

解析json的核心代码只有这两行:

               

解析后的weather在控制台输出为:

{"weatherinfo":{"city":"北京","cityid":"101010100","temp1":"-5℃","temp2":"6℃","weather":"阴转晴","img1":"n2.gif","img2":"d0.gif","ptime":"18:00"}}

这样就实现了这个小程序,下一篇文章将在此基础上稍作些扩展 。


如果有任何建议和意见或者是有错误,恳请大家指出。o(∩∩)o...


0 0
原创粉丝点击