java获取天气接口
生活随笔
收集整理的這篇文章主要介紹了
java获取天气接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如下圖
package com.octv.board.common.utils;import java.io.*; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLConnection; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import com.alibaba.fastjson.JSONObject; import com.octv.common.utils.StringUtils; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; /*** java調用中央氣象局天氣預報接口 ** @author Administrator**/ public class WeatherUtil {/**** 獲取實時天氣1<br> * 方 法 名: getTodayWeather <br> ** 城市編碼 */public static Map<String, Object> getTodayWeather1()throws IOException, NullPointerException {String areaId = area();// 連接中央氣象臺的API URL url = new URL("http://api.k780.com:88/?app=weather.today&weaid=" + 101280601 + "&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=xml");URLConnection connectionData = url.openConnection();connectionData.setConnectTimeout(2000);Map<String, Object> weathermap = new HashMap<String, Object>();try {BufferedReader br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));StringBuilder sb = new StringBuilder();String line = null;while ((line = br.readLine()) != null)sb.append(line);String xmlString = sb.toString();Document document = DocumentHelper.parseText(xmlString);List bodyInfoList = document.selectNodes("//root");Iterator iterator = bodyInfoList.iterator();while (iterator.hasNext()) {Element bodyInfoElement = (Element) iterator.next();// 解析 school,針對單個,對方文檔已經說明了就是一個Iterator weatherIterator = bodyInfoElement.elementIterator("result");while (weatherIterator.hasNext()) {Element element = (Element) weatherIterator.next();weathermap.put("city", getElementText(element, "citynm"));weathermap.put("weather_curr", getElementText(element, "weather_curr"));weathermap.put("temperature", getElementText(element, "temperature"));weathermap.put("temperature_curr", getElementText(element, "temperature_curr"));weathermap.put("temp_high", getElementText(element, "temp_high"));weathermap.put("temp_low", getElementText(element, "temp_low"));weathermap.put("wind", getElementText(element, "wind"));weathermap.put("winp", getElementText(element, "winp"));}}} catch (DocumentException e) {e.printStackTrace();}return weathermap;}/*** 功能描述:獲取xml元素值** @param element* @param elementIteratorName* @return*/public static String getElementText(Element element, String elementIteratorName) {Iterator iterator = element.elementIterator(elementIteratorName);if (iterator.hasNext()) {Element subElement = (Element) iterator.next();return subElement.getText();}return null;}/**** 獲取實時天氣1<br>* 方 法 名: getTodayWeather <br>** 城市編碼*/public static Map<String, Object> getTodayWeather3()throws IOException, NullPointerException {String areaId=area();// 連接中央氣象臺的APIURL url = new URL("http://api.k780.com:88/?app=weather.today&weaid="+101280601+"&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=xml");URLConnection connectionData = url.openConnection();connectionData.setConnectTimeout(2000);Map<String, Object> map = new HashMap<String, Object>();try {BufferedReader br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));StringBuilder sb = new StringBuilder();String line = null;while ((line = br.readLine()) != null)sb.append(line);String datas = sb.toString();map.put("city", cutString(datas,"<citynm>","</citynm>"));// 城市map.put("weather_curr", cutString(datas,"<weather_curr>","</weather_curr>"));// 天氣描述map.put("temperature", cutString(datas,"<temperature>","</temperature>"));// 溫度map.put("temperature_curr", cutString(datas,"<temperature_curr>","</temperature_curr>"));// 平均溫度map.put("temp_high", cutString(datas,"<temp_high>","</temp_high>"));// 溫度map.put("temp_low", cutString(datas,"<temp_low>","</temp_low>"));// 溫度map.put("wind", cutString(datas,"<wind>","</wind>"));// 溫度map.put("winp", cutString(datas,"<winp>","</winp>"));// 風速} catch (SocketTimeoutException e) {System.out.println("連接超時");} catch (FileNotFoundException e) {System.out.println("加載文件出錯");}return map;}/**** 獲取實時天氣2<br> * 方 法 名: getTodayWeather <br> ** @param Cityid* 城市編碼 */public static Map<String, Object> getTodayWeather2(String Cityid)throws IOException, NullPointerException {// 連接中央氣象臺的API URL url = new URL("http://www.weather.com.cn/data/cityinfo/" + Cityid+ ".html");URLConnection connectionData = url.openConnection();connectionData.setConnectTimeout(1000);Map<String, Object> map = new HashMap<String, Object>();try {BufferedReader br = new BufferedReader(new InputStreamReader(connectionData.getInputStream(), "UTF-8"));StringBuilder sb = new StringBuilder();String line = null;while ((line = br.readLine()) != null)sb.append(line);String datas = sb.toString();System.out.println(datas);//JSONObject jsonData = JSONObject.fromObject(jsonData);//JSONObject jsonData = new JSONObject(jsonData);JSONObject jsonData = JSONObject.parseObject(datas);JSONObject info = jsonData.getJSONObject("weatherinfo");map.put("city", info.getString("city").toString());// 城市 map.put("temp1", info.getString("temp1").toString());// 最高溫度 map.put("temp2", info.getString("temp2").toString());// 最低溫度 map.put("weather", info.getString("weather").toString());//天氣 map.put("ptime", info.getString("ptime").toString());// 發布時間 } catch (SocketTimeoutException e) {System.out.println("連接超時");} catch (FileNotFoundException e) {System.out.println("加載文件出錯");}return map;}public static String area(){String result = HttpUtil.get("http://api.k780.com:88/?app=weather.city&format=xml", 1000);if (StrUtil.isNotBlank(result)) {String reg= "<msgid>" + "(.*)" + "</msgid>";Pattern pattern = Pattern.compile(reg);Matcher matcher = pattern.matcher(result);while (matcher.find()) {result = matcher.group(1);}}return result;}public static String cutString(String str, String start, String end) {if (StringUtils.isBlank(str)) {return str;}String reg= start + "(.*)" + end;Pattern pattern = Pattern.compile(reg);Matcher matcher = pattern.matcher(str);while (matcher.find()) {str = matcher.group(1);}return str;} }有一些沒有的,解析xml方式有暴力截取
總結
以上是生活随笔為你收集整理的java获取天气接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: wamp mysql 环境变量_wind
- 下一篇: Pointofix安装与设置为中文