首页 > 编程语言 > 详细

JAVA获取天气

时间:2014-12-10 02:11:01      阅读:286      评论:0      收藏:0      [点我收藏+]

?

package javaapplication1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Weather {
	public static String getWeather(String cityCode) {
		String result = "";
		Pattern pattern = Pattern.compile(".*?\"weather\":\"(.*?)\",.*");
		try {
			URL url = new URL("http://www.weather.com.cn/data/cityinfo/" + cityCode + ".html");
			InputStream in = url.openStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
			String line = br.readLine();
			if(null == line) {
				return result;
			} else {
				Matcher matcher = pattern.matcher(line);
				if(matcher.find()) {
					result = matcher.group(1);
				}
			}
			System.out.println(line);
			br.close();
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public static void main(String[] args) {
		System.out.println(Weather.getWeather("101110101"));
	}
}

?

?

运行结果 :

{"weatherinfo":{"city":"西安","cityid":"101110101","temp1":"4℃","temp2":"0℃","weather":"雨夹雪转小雪","img1":"d6.gif","img2":"n14.gif","ptime":"11:00"}}
雨夹雪转小雪

?用json解析是最合适的,但不想引入其他包,直接用正则解析了。

城市代码表见附件。

?

JAVA获取天气

原文:http://superlxw1234.iteye.com/blog/2164434

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!