1、開通接口
天氣預報接口服務使用的聚合數據提供的免費接口,每天可以100次免費調用。可以通過https://www.juhe.cn/docs/api/id/73注冊及開通。
2、通過Java發起城市天氣查詢
package cn.juhe; import net.sf.json.JSONObject; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class SimpleWeather { // 天氣情況查詢接口地址 public static String API_URL = "http://apis.juhe.cn/simpleWeather/query"; // 接口請求Key public static String API_KEY = "xxxxxxxxxxxxxx"; public static void main(String[] args) { String cityName = "北京"; queryWeather(cityName); } /** * 根據城市名查詢天氣情況 * * @param cityName */ public static void queryWeather(String cityName) { Map<String, Object> params = new HashMap<>();//組合參數 params.put("city", cityName); params.put("key", API_KEY); String queryParams = urlencode(params); String response = doGet(API_URL, queryParams); try { JSONObject jsonObject = JSONObject.fromObject(response); int error_code = jsonObject.getInt("error_code"); if (error_code == 0) { System.out.println("調用接口成功"); JSONObject result = jsonObject.getJSONObject("result"); JSONObject realtime = result.getJSONObject("realtime"); System.out.printf("城市:%s%n", result.getString("city")); System.out.printf("天氣:%s%n", realtime.getString("info")); System.out.printf("溫度:%s%n", realtime.getString("temperature")); System.out.printf("濕度:%s%n", realtime.getString("humidity")); System.out.printf("風向:%s%n", realtime.getString("direct")); System.out.printf("風力:%s%n", realtime.getString("power")); System.out.printf("空氣質量:%s%n", realtime.getString("aqi")); } else { System.out.println("調用接口失敗:" + jsonObject.getString("reason")); } } catch (Exception e) { e.printStackTrace(); } } /** * get方式的http請求 * * @param httpUrl 請求地址 * @return 返回結果 */ public static String doGet(String httpUrl, String queryParams) { HttpURLConnection connection = null; InputStream inputStream = null; BufferedReader bufferedReader = null; String result = null;// 返回結果字符串 try { // 創建遠程url連接對象 URL url = new URL(new StringBuffer(httpUrl).append("?").append(queryParams).toString()); // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類 connection = (HttpURLConnection) url.openConnection(); // 設置連接方式:get connection.setRequestMethod("GET"); // 設置連接主機服務器的超時時間:15000毫秒 connection.setConnectTimeout(5000); // 設置讀取遠程返回的數據時間:60000毫秒 connection.setReadTimeout(6000); // 發送請求 connection.connect(); // 通過connection連接,獲取輸入流 if (connection.getResponseCode() == 200) { inputStream = connection.getInputStream(); // 封裝輸入流,並指定字符集 bufferedReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); // 存放數據 StringBuilder sbf = new StringBuilder(); String temp; while ((temp = bufferedReader.readLine()) != null) { sbf.append(temp); sbf.append(System.getProperty("line.separator")); } result = sbf.toString(); } } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != bufferedReader) { try { bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != inputStream) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect();// 關閉遠程連接 } } return result; } /** * 將map型轉為請求參數型 * * @param data * @return */ public static String urlencode(Map<String, ?> data) { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, ?> i : data.entrySet()) { try { sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } String result = sb.toString(); result = result.substring(0, result.lastIndexOf("&")); return result; } }