JAVA的免費天氣api接口調用示例


step1:選擇本文所示例的接口"免費天氣api" url:https://www.juhe.cn/docs/api/id/39/aid/87

step2:每個接口都需要傳入一個參數key,相當於用戶的令牌,所以第一步你需要申請一個key

step3:看文檔!!!學過java的同學們都知道,當我們對一個類或者方法不明白其意圖和思想時,我們可以去查看文檔,這里也不例外,而且對於英文不是特別好的同學來說很幸運的是,聚合網站上的文檔都是中文版本的,比起閱讀java源碼里的英文文檔應該輕松很多.

全國天氣預報接口下面有六個子接口,打開第一個接口鏈接,看文檔發現需要傳入一個城市名或者城市ID參數,這個參數我們可以通過第六個子接口獲取(接口之間參數的調用類似於java中方法之間的調用),即支持城市列表獲取.所以示例中我們先調用這個接口.調用接口涉及到請求網絡資源的問題,這里我封裝了一個工具類,包含GET和POST兩種方法

step4:上代碼

Demo1:網絡訪問工具類(封裝get和post方法)

Java代碼   收藏代碼
  1. package juheAPI;  
  2.     
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.OutputStream;  
  8. import java.io.OutputStreamWriter;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11. import java.util.Map;  
  12. /** 
  13.  * 網絡訪問工具類 
  14.  * @author silk 
  15.  * 
  16.  */  
  17. public class PureNetUtil {  
  18.     /** 
  19.      * get方法直接調用post方法 
  20.      * @param url 網絡地址 
  21.      * @return 返回網絡數據 
  22.      */  
  23.     public static String get(String url){  
  24.         return post(url,null);  
  25.     }  
  26.     /** 
  27.      * 設定post方法獲取網絡資源,如果參數為null,實際上設定為get方法 
  28.      * @param url 網絡地址 
  29.      * @param param 請求參數鍵值對 
  30.      * @return 返回讀取數據 
  31.      */  
  32.    public static <K, V> String post(String  url,Map<K,V>   param){  
  33.         HttpURLConnection conn=null;  
  34.         try {  
  35.             URL u=new URL(url);  
  36.             conn=(HttpURLConnection) u.openConnection();  
  37.             StringBuffer sb=null;  
  38.             if(param!=null){//如果請求參數不為空  
  39.                 sb=new StringBuffer();  
  40.                 /*A URL connection can be used for input and/or output.  Set the DoOutput 
  41.                  * flag to true if you intend to use the URL connection for output, 
  42.                  * false if not.  The default is false.*/  
  43.                 //默認為false,post方法需要寫入參數,設定true  
  44.                 conn.setDoOutput(true);  
  45.                 //設定post方法,默認get  
  46.                 conn.setRequestMethod("POST");  
  47.                 //獲得輸出流  
  48.                 OutputStream out=conn.getOutputStream();  
  49.                 //對輸出流封裝成高級輸出流  
  50.                 BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));  
  51.                 //將參數封裝成鍵值對的形式  
  52.                 for(Map.Entry s:param.entrySet()){  
  53.                     sb.append(s.getKey()).append("=").append(s.getValue()).append("&");  
  54.                 }  
  55.                 //將參數通過輸出流寫入  
  56.                 writer.write(sb.deleteCharAt(sb.toString().length()-1).toString());  
  57.                 writer.close();//一定要關閉,不然可能出現參數不全的錯誤  
  58.                 sb=null;  
  59.             }  
  60.             conn.connect();//建立連接  
  61.             sb=new StringBuffer();  
  62.             //獲取連接狀態碼  
  63.             int recode=conn.getResponseCode();  
  64.             BufferedReader reader=null;  
  65.             if(recode==200){  
  66.                 //Returns an input stream that reads from this open connection  
  67.                 //從連接中獲取輸入流  
  68.                 InputStream in=conn.getInputStream();  
  69.                 //對輸入流進行封裝  
  70.                 reader=new BufferedReader(new InputStreamReader(in));  
  71.                 String str=null;  
  72.                 sb=new StringBuffer();  
  73.                 //從輸入流中讀取數據  
  74.                 while((str=reader.readLine())!=null){  
  75.                     sb.append(str).append(System.getProperty("line.separator"));  
  76.                 }  
  77.                 //關閉輸入流  
  78.                 reader.close();  
  79.                 if (sb.toString().length() == 0) {  
  80.                     return null;  
  81.                 }  
  82.                 return sb.toString().substring(0,  
  83.                         sb.toString().length() - System.getProperty("line.separator").length());  
  84.             }  
  85.         } catch (Exception e) {  
  86.             e.printStackTrace();  
  87.             return null;  
  88.         }finally{  
  89.             if(conn!=null)//關閉連接  
  90.                 conn.disconnect();  
  91.         }  
  92.         return null;  
  93.     }  
  94.     
  95. }  

Demo2:調用獲取城市列表接口示例

Java代碼   收藏代碼
  1. package juheAPI;  
  2.    
  3. import net.sf.json.JSONArray;  
  4. import net.sf.json.JSONObject;  
  5.    
  6.    
  7. /** 
  8.  * 獲取城市列表 
  9.  * 全國天氣預報接口調用JAVA示例 
  10.  *     dtype     string    N    返回數據格式:json或xml,默認json     
  11.  *     key        string     Y    你申請的key     
  12.  * @author silk 
  13.  * 
  14.  */  
  15. public class GetCityList {  
  16.     /** 
  17.      * 調用獲取城市列表接口,返回所有數據 
  18.      * @return 返回接口數據 
  19.      */  
  20.     public static String excute(){  
  21.         String url="http://v.juhe.cn/weather/citys?key=***a7558b2e0bedaa19673f74a6809ce";//接口URL  
  22.         //PureNetUtil是一個封裝了get和post方法獲取網絡請求數據的工具類  
  23.         return PureNetUtil.get(url);//使用get方法  
  24.     }  
  25.     /** 
  26.      * 調用接口返回數據后,解析數據,根據輸入城市名得到對應ID 
  27.      * @param cityName 城市名稱 
  28.      * @return 返回對應ID 
  29.      */  
  30.     public static String getIDBycityName(String cityName) {  
  31.         String result=excute();//返回接口結果,得到json格式數據  
  32.         if(result!=null){  
  33.             JSONObject obj=JSONObject.fromObject(result);  
  34.             result=obj.getString("resultcode");//得到返回狀態碼  
  35.             if(result!=null&&result.equals("200")){//200表示成功返回數據  
  36.                 result=obj.getString("result");//得到城市列表的json格式字符串數組  
  37.                 JSONArray arr=JSONArray.fromObject(result);  
  38.                 for(Object o:arr){//對arr進行遍歷  
  39.                     //將數組中的一個json個數字符串進行解析  
  40.                     obj=JSONObject.fromObject(o.toString());  
  41.                     /*此時obj如 {"id":"2","province":"北京","city":"北京","district":"海淀"}*/  
  42.                     //以city這個key為線索判斷所需要尋找的這條記錄  
  43.                     result=obj.getString("district");  
  44.                     //防止輸入城市名不全,如蘇州市輸入為蘇州,類似與模糊查詢  
  45.                     if(result.equals(cityName)||result.contains(cityName)){  
  46.                         result=obj.getString("id");//得到ID  
  47.                         return result;  
  48.                     }  
  49.                 }  
  50.             }  
  51.         }  
  52.         return result;  
  53.     }  
  54.     public static void main(String[] args) {  
  55.         System.out.println(getIDBycityName("香港"));  
  56.     }  
  57. }  

 Demo3:調用根據城市名/id查詢天氣

Java代碼   收藏代碼
  1. package juheAPI;  
  2.    
  3. import net.sf.json.JSONObject;  
  4.    
  5.    
  6. /** 
  7.  * 根據城市名/id查詢天氣 
  8.  * @author silk 
  9.  * 
  10.  */  
  11. public class WeatherReportByCity {  
  12.     /** 
  13.      * 根據城市名獲取 
  14.      * @param cityName 
  15.      * @return 
  16.      */  
  17.     public static String excute(String cityName){  
  18.         String url=//此處以返回json格式數據示例,所以format=2,以根據城市名稱為例,cityName傳入中文  
  19.                 "http://v.juhe.cn/weather/index?cityname="+cityName+"&key=***a7558b2e0bedaa19673f74a6809ce";  
  20.         return PureNetUtil.get(url);//通過工具類獲取返回數據  
  21.     }  
  22.     /** 
  23.      * 獲取返回數據中的一個屬性示例,此處以獲取今日溫度為例 
  24.      * "temperature": "8℃~20℃"     今日溫度 
  25.      * @param args 
  26.      * @return  
  27.      */  
  28.     public static String GetTodayTemperatureByCity(String city) {  
  29.         String result=excute(city);  
  30.         if(result!=null){  
  31.             JSONObject obj=JSONObject.fromObject(result);  
  32.             /*獲取返回狀態碼*/  
  33.             result=obj.getString("resultcode");  
  34.             /*如果狀態碼是200說明返回數據成功*/  
  35.             if(result!=null&&result.equals("200")){  
  36.                 result=obj.getString("result");  
  37.                 //此時result中數據有多個key,可以對其key進行遍歷,得到對個屬性  
  38.                 obj=JSONObject.fromObject(result);  
  39.                 //今日溫度對應的key是today  
  40.                 result=obj.getString("today");  
  41.                 obj=JSONObject.fromObject(result);  
  42.                 //今日溫度對應當key是temperature  
  43.                 result=obj.getString("temperature");  
  44.                 return result;  
  45.             }  
  46.         }  
  47.         return result;  
  48.     }  
  49.     public static void main(String[] args) {  
  50.         System.out.println(GetTodayTemperatureByCity("蘇州"));  
  51.     }  
  52. }  

 Demo4:調用天氣種類及表示列表接口示例

Java代碼   收藏代碼
  1. package juheAPI;  
  2.    
  3. import net.sf.json.JSONArray;  
  4. import net.sf.json.JSONObject;  
  5.    
  6.    
  7. /** 
  8.  * 天氣種類及標識列表接口調用JAVA示例 
  9.  * @author silk 
  10.  */  
  11. public class GetWeatherSignAndTypeList {  
  12.     //接口地址,因為只需要傳入一個固定的key為參數,所以設為常量  
  13.     private static final String URL= "http://v.juhe.cn/weather/uni?key=***a7558b2e0bedaa19673f74a6809ce";  
  14.     /** 
  15.      * 通過工具類獲取數據 
  16.      * @return 
  17.      */  
  18.     public static String excute(){  
  19.         return PureNetUtil.get(URL);//調用工具類獲取接口數據  
  20.     }  
  21.     /** 
  22.      * 利用遍歷數組的方式獲取 
  23.      * @param wid天氣對應id 
  24.      * @return 天氣名稱 
  25.      */  
  26.     public static String getWeatherByWid(String wid) {  
  27.         String result=excute();//獲取接口數據  
  28.         if(result!=null){  
  29.             JSONObject obj=JSONObject.fromObject(result);  
  30.             result=obj.getString("resultcode");  
  31.             /*獲取返回狀態碼*/  
  32.             if(result!=null&&result.equals("200")){  
  33.                 /*獲取數組數據*/  
  34.                 result=obj.getString("result");  
  35.                 JSONArray arr=JSONArray.fromObject(result);  
  36.                 for(Object o:arr){//遍歷數組  
  37.                     obj=JSONObject.fromObject(o.toString());  
  38.                     //如果遍歷到需要的數據后直接返回結果,根據key(wid)得到value判斷是否等於傳入參數  
  39.                     if(obj.getString("wid").equals(wid)){  
  40.                         result=obj.getString("weather");  
  41.                         return result;  
  42.                     }  
  43.                 }  
  44.             }  
  45.         }  
  46.         return result;  
  47.     }  
  48.     public static void main(String[] args) {  
  49.         System.out.println(getWeatherByWid("10"));  
  50.     }  
  51. }  

  step5:調用接口時候如果狀態碼不是200,仔細參考文檔說明,也就是返回step3:看文檔!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM