内容摘要:
通过自动任务实时获取城市天气信息,插入到表中
//自动抓取港口天气
@Component("autoUpdateWeatherInfo")
public class AutoUpdateWeatherInfo {
@Autowired
private ITbWeatherInfoService tbWeatherInfoService;
private final String[] PORT_CODE = {"120116","130209","130983","130225"};
public void selectWeatherInfo(){
String URL = "https://restapi.amap.com/v3/weather/weatherInfo";
String GAODEI_KEY_LIKUN = "a4e02dad1f9cb9ee674cff2fb0b124b0";
for (String port_code : PORT_CODE) {
JSONObject jsonObject = doGet(URL + "?key=" + GAODEI_KEY_LIKUN + "&city=" + port_code);
JSONArray lives = jsonObject.getJSONArray("lives");
JSONObject object = (JSONObject) lives.get(0);
TbWeatherInfo tbWeatherInfo = new TbWeatherInfo();
tbWeatherInfo.setWeather(object.get("weather").toString());
switch (port_code){
case "120116":
tbWeatherInfo.setPort("天津港");
break;
case "130209":
tbWeatherInfo.setPort("曹妃甸港");
break;
case "130983":
tbWeatherInfo.setPort("黄骅港");
break;
case "130225":
tbWeatherInfo.setPort("京唐港");
break;
}
tbWeatherInfo.setWindDirection(object.get("winddirection").toString());
tbWeatherInfo.setWindPower(object.get("windpower").toString());
tbWeatherInfo.setTemperature(object.get("temperature").toString());
tbWeatherInfo.setUpdateTime(DateUtils.getTime());
tbWeatherInfoService.insertTbWeatherInfo(tbWeatherInfo);
}
}
/**
* 以get方式调用对方接口方法
* @param pathUrl
*/
public static JSONObject doGet(String pathUrl){
JSONObject jsonObject = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设定请求的方法为"GET",默认是GET
//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setRequestMethod("GET");
//设置30秒连接超时
conn.setConnectTimeout(30000);
//设置30秒读取超时
conn.setReadTimeout(30000);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// Post请求不能使用缓存(get可以不使用)
conn.setUseCaches(false);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //维持长链接
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
/**
* 下面的代码相当于,获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
jsonObject = JSONObject.fromObject(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return jsonObject;
}
}