package com.zx.cn.example.tianqi;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.IOUtils; //需要导入此包commons.io
//需要6个包 :json-lib-2.4-jdk15.jar 2、commons-beanutils 3、commons-collections 4、commons-lang 5、commons-logging 6、ezmorph
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* 今天做了个小练习,使用的是知心天气API接口 太小的地方天气查不出来。
* @author 张艺馨
*
*/
class WeatherForecast {
private String TIANQI_DAILY_WEATHER_URL = "https://api.seniverse.com/v3/weather/daily.json";
private String TIANQI_API_SECRET_KEY = "r2nz6zbukfdycceu"; //YOUR API KEY 我的密钥
private String TIANQI_API_USER_ID = "UFD9429836"; //YOUR USER ID 我的帐号
/**
* Generate HmacSHA1 signature with given data string and key
* @param data
* @param key
* @return
* @throws SignatureException
*/
private String generateSignature(String data, String key) throws SignatureException {
String result;
try {
// get an hmac_sha1 key from the raw key bytes
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
// get an hmac_sha1 Mac instance and initialize with the signing key
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
// compute the hmac on input data bytes
byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
result = new sun.misc.BASE64Encoder().encode(rawHmac);
}
catch (Exception e) {
throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
}
return result;
}
/**
* Generate the URL to get diary weather
* @param location
* @param language
* @param unit
* @param start
* @param days
* @return
*/
public String generateGetDiaryWeatherURL(
String location,
String language,
String unit,
String start,
String days
) throws SignatureException, UnsupportedEncodingException {
String city = java.net.URLEncoder.encode(location, "utf-8");
String timestamp = String.valueOf(new Date().getTime());
String params = "ts=" + timestamp + "&ttl=30&uid=" + TIANQI_API_USER_ID;
String signature = URLEncoder.encode(generateSignature(params, TIANQI_API_SECRET_KEY), "UTF-8");
return TIANQI_DAILY_WEATHER_URL + "?" + params + "&sig=" + signature + "&location=" + city + "&language=" + language + "&unit=" + unit + "&start=" + start + "&days=" + days;
}
/**
* 发送请求,获取json数据
* @param apiUrl 访问的url
* @return 返回json数据
* @throws Exception
*/
public static String json(String apiUrl) throws Exception{
//开始请求
URL url= new URL(apiUrl);
URLConnection open = url.openConnection();
InputStream input = open.getInputStream();
//这里转换为String,带上包名,怕你们引错包
String result = IOUtils.toString(input,"utf-8");
//输出
//System.out.println(result);
return result;
}
/**
* 解析json串
* {"results":
* [{"location":
* {"id":"WX4FBXXFKE4F","name":"北京","country":"CN","path":"北京,北京,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"
* },
* "daily":[{
* "date":"2018-05-03","text_day":"晴","code_day":"0","text_night":"晴","code_night":"1","high":"24","low":"12","precip":"","wind_direction":"北","wind_direction_degree":"0","wind_speed":"15","wind_scale":"3"
* },
* {"date":"2018-05-04","text_day":"晴","code_day":"0","text_night":"多云","code_night":"4","high":"27","low":"16","precip":"","wind_direction":"西南","wind_direction_degree":"225","wind_speed":"15","wind_scale":"3"
* }],
* "last_update":"2018-05-02T11:00:00+08:00"}
* ]}
* @param parameter
* @return
* @throws Exception
*/
public static List jsonToObject(String parameter) throws Exception{
JSONObject jsonObject = JSONObject.fromObject(parameter); //将String 转成 json
String location =jsonObject.getJSONArray("results").getJSONObject(0).getString("location");//{"id":"WX4FBXXFKE4F","name":"北京","country":"CN","path":"北京,北京,中国","timezone":"Asia/Shanghai","timezone_offset":"+08:00"}
JSONObject city = JSONObject.fromObject(location);
String name = city.getString("name");//地点
String last_update =jsonObject.getJSONArray("results").getJSONObject(0).getString("last_update");//最后的更新时间。
Map hMap =new HashMap();
hMap.put("地点",name);
hMap.put("最后的更新时间",last_update);
List list =new ArrayList();
list.add(hMap);
// 返回json的数组
JSONArray jsonArray =jsonObject.getJSONArray("results").getJSONObject(0).getJSONArray("daily");
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
//创建JsonObject第二种方法
HashMap hashMap = new HashMap();
hashMap.put("日期", jsonObject2.getString("date"));//时间
hashMap.put("白天", jsonObject2.getString("text_day"));//白天
hashMap.put("夜间", jsonObject2.getString("text_night"));//夜间
hashMap.put("最高气温", jsonObject2.getString("high"));//最高气温
hashMap.put("最低气温", jsonObject2.getString("low"));//最低气温
hashMap.put("降水概率", jsonObject2.getString("precip"));//降水概率,范围0~100,单位百分比
hashMap.put("风向", jsonObject2.getString("wind_direction"));//风向
hashMap.put("风向角度", jsonObject2.getString("wind_direction_degree"));//风向角度,范围0~360
hashMap.put("风速", jsonObject2.getString("wind_speed"));//风速,单位km/h(当unit=c时)、mph(当unit=f时)
hashMap.put("风力等级", jsonObject2.getString("wind_scale"));//风力等级
//System.out.println("jsonObject2:" + JSONObject.fromObject(hashMap));
list.add(hashMap);
}
return list;
}
public static void main(String args[]){
WeatherForecast demo = new WeatherForecast();
try {
Scanner sc =new Scanner(System.in);
System.out.println("请输入要查询天气的城市");
while(true){
String city = sc.nextLine();
if(city.length()>0){
String url = demo.generateGetDiaryWeatherURL(
city,
"zh-Hans",
"c",
"0",
"5"
);
String json= WeatherForecast.json(url);
List list =jsonToObject(json);
for(int i = 0 ;i
if(i==0){
System.out.println("城市:"+list.get(i).get("地点"));
}else{
Map map =list.get(i);
System.out.println("时间:"+map.get("日期")+" *白天-夜间:"+map.get("白天")+" 转 "+map.get("夜间")+" *气温:"+map.get("最低气温")+"--"+map.get("最高气温")+"(度)"+" *风力:"+map.get("风力等级")+"级"+"风速:"+map.get("风速")+"单位km/h");
}
}
System.out.println("请输入要查询天气的城市,结束查询请按回车键!");
}else{
break;
}
}
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}