通过天气信息接口获取天气信息,首先要给项目导入程序所需要的包,具体需要如下几个包:
源码如下:
1 package com.web.test; 2 3 import java.io.BufferedReader; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.io.InputStreamReader; 7 import java.net.SocketTimeoutException; 8 import java.net.URL; 9 import java.net.URLConnection; 10 import java.util.HashMap; 11 import java.util.Map; 12 13 import net.sf.json.JSONObject; 14 15 public class WeatherHelper { 16 17 /** 18 * @param args 19 * @throws IOException 20 */ 21 public static void main(String[] args) throws IOException { 22 // TODO Auto-generated method stub 23 System.out.println(getWeather("101010100"));//北京的天气信息 24 System.out.println(getWeather("101010100").get("date").toString()); 25 } 26 27 /** 28 * 获得天气信息 29 * @param cityid 城市ID 30 * @return 天气信息 31 * @throws IOException 32 */ 33 public static Map<String, String> getWeather(String cityid) throws IOException{ 34 String weather = ""; 35 URLConnection connectionData; 36 BufferedReader br;// 读取data数据流 37 StringBuilder sb = null; 38 39 // 连接中央气象台的API 40 URL url = new URL("http://m.weather.com.cn/data/" + cityid + ".html"); 41 connectionData = url.openConnection(); 42 connectionData.setConnectTimeout(1000); 43 try { 44 br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8")); 45 sb = new StringBuilder(); 46 String line = null; 47 while ((line = br.readLine()) != null) 48 sb.append(line); 49 } catch (SocketTimeoutException e) { 50 System.out.println("连接超时"); 51 } catch (FileNotFoundException e) { 52 System.out.println("加载文件出错"); 53 } 54 weather = sb.toString(); 55 System.out.println(weather); 56 JSONObject jsonData = JSONObject.fromObject(weather); 57 JSONObject jsonWeather = jsonData.getJSONObject("weatherinfo"); 58 Map<String, String> weatherInfo = new HashMap<String, String>(); 59 weatherInfo.put("cityId", jsonWeather.getString("cityid").toString());//id 60 weatherInfo.put("cityName", jsonWeather.getString("city").toString());//名称 61 weatherInfo.put("date", jsonWeather.getString("date_y").toString());//日期 62 weatherInfo.put("week", jsonWeather.getString("week").toString());//星期 63 weatherInfo.put("temp", jsonWeather.getString("temp1").toString());//温度 64 weatherInfo.put("weather", jsonWeather.getString("weather1").toString());//天气现象 65 weatherInfo.put("wind", jsonWeather.getString("wind1").toString());//风 66 weatherInfo.put("fl", jsonWeather.getString("fl1").toString());//风力 67 weatherInfo.put("fx", jsonWeather.getString("fx1").toString());//风向 68 69 return weatherInfo; 70 } 71 72 }