java调天气预报接口


1、java调用天气预报接口,参考http://g.kehou.com/t1029846752.html,现在比如我访问成都的天气预报,则访问地址http://m.weather.com.cn/data/101270101.html,就可一得到一串json数据。我们就可以对这串进行解析

如果用ajax直接访问是最简单的一种方式,但涉及到一个跨域的问题,至今都还没搞懂啊,跪求大神
现在用java解析就变得比较简单,上代码:

@GET
	@Path("/get")
	@Produces(MediaType.APPLICATION_JSON)
	public String getWeather() throws MalformedURLException, IOException,
			JSONException {

		try {
			HttpURLConnection huc = (HttpURLConnection) new URL(
					"http://m.weather.com.cn/data/101270101.html")
					.openConnection();
			huc.setRequestMethod("GET");
			huc.setUseCaches(true);
			huc.connect();
			InputStream is = huc.getInputStream();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			StringBuffer temp = new StringBuffer();
			String str;
			while ((str = reader.readLine()) != null) {
				temp.append(str + "\n");
			}
			System.out.println(temp.toString());
			is.close();
			reader.close();
			return temp.toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			
		}
		return null;
	}



2、这里用到的是restful,无所谓用什么,我们用ajax调用到这个方法时就会返回一串json数据到前台如代码,

function getWeather() {
	
	$.ajax({
		url : 'rest/weather/get',
		type : 'GET',
		success : function(meta) {
			var w = meta.weatherinfo;
			$("#w1").empty().append("今天:"+w.weather1+"  "+w.temp1+"  <img src='http://www.weather.com.cn/m/i/weatherpic/29x20/d"+w.img1+".gif'></img>");
			$("#w2").empty().append("明天:"+w.weather2+"  "+w.temp2+"  <img src='http://www.weather.com.cn/m/i/weatherpic/29x20/d"+w.img3+".gif'></img>");
			$("#w3").empty().append("后天:"+w.weather3+"  "+w.temp3+"  <img src='http://www.weather.com.cn/m/i/weatherpic/29x20/d"+w.img5+".gif'></img>");
		}
	});
}


ajax可能就是解析一个json数据。。。
注:img中装的是天气预报提供的表示各种天气的图片,参考http://g.kehou.com/t1029846752.html 讲的很清楚。
差不多了。。。

猜你喜欢

转载自rguess.iteye.com/blog/1681223