?
class="java" name="code">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解析是最合适的,但不想引入其他包,直接用正则解析了。
城市代码表见附件。
?