【java写的未来6天的天气预报】
最近写的一个java程序,
需求:获取未来6天的天气预报,条用中央气象台API来实现的
有兴趣的同学可以,参考一下:代码如下
[java] view plaincopyprint?
package com.xuan.service;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
public class Weather {
private String Cityid;
private URLConnection connectionData;
private StringBuilder sb;
private BufferedReader br;// 读取data数据流
private JSONObject jsonData;
private JSONObject info;
public Weather(String cityid) throws IOException{
///解析本机IP地址
this.Cityid=cityid;
///连接中央气象台的APi
URL url=new URL("m.weathercn/data/" + Cityid + ".html");
connectionData = url.openConnection();
connectionData.setConnectTimeout(1000);
try {
br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null){
sb.append(line);
}
} catch (SocketTimeoutException e) {
System.out.println("连接超时");
} catch (FileNotFoundException e) {
System.out.println("加载文件出错");
}
String datas = sb.toString();
jsonData = JSONObject.fromObject(datas);
// System.out.println(jsonData.toString());
info = jsonData.getJSONObject("weatherinfo");
//得到1到6天的天气情况
List<Map<String,Object》 list =new ArrayList<Map<String,Object》();
for(int i=1;i<=6;i++){
//得到未来6天的日期
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, i-1);
Date date = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月dd日");
Map<String,Object> map = new HashMap<String, Object>();
map.put("city", info.getString("city")。toString());//城市
map.put("date_y", sf.format(date));//日期
map.put("week", getWeek(cal.get(Calendar.DAY_OF_WEEK)));//星期
map.put("fchh", info.getString("fchh")。toString());//发布时间
map.put("weather", info.getString("weather"+i)。toString());//天气
map.put("temp", info.getString("temp"+i)。toString());//温度
map.put("wind", info.getString("wind"+i)。toString());//风况