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方法)
- package juheAPI;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.Map;
- /**
- * 網絡訪問工具類
- * @author silk
- *
- */
- public class PureNetUtil {
- /**
- * get方法直接調用post方法
- * @param url 網絡地址
- * @return 返回網絡數據
- */
- public static String get(String url){
- return post(url,null);
- }
- /**
- * 設定post方法獲取網絡資源,如果參數為null,實際上設定為get方法
- * @param url 網絡地址
- * @param param 請求參數鍵值對
- * @return 返回讀取數據
- */
- public static <K, V> String post(String url,Map<K,V> param){
- HttpURLConnection conn=null;
- try {
- URL u=new URL(url);
- conn=(HttpURLConnection) u.openConnection();
- StringBuffer sb=null;
- if(param!=null){//如果請求參數不為空
- sb=new StringBuffer();
- /*A URL connection can be used for input and/or output. Set the DoOutput
- * flag to true if you intend to use the URL connection for output,
- * false if not. The default is false.*/
- //默認為false,post方法需要寫入參數,設定true
- conn.setDoOutput(true);
- //設定post方法,默認get
- conn.setRequestMethod("POST");
- //獲得輸出流
- OutputStream out=conn.getOutputStream();
- //對輸出流封裝成高級輸出流
- BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(out));
- //將參數封裝成鍵值對的形式
- for(Map.Entry s:param.entrySet()){
- sb.append(s.getKey()).append("=").append(s.getValue()).append("&");
- }
- //將參數通過輸出流寫入
- writer.write(sb.deleteCharAt(sb.toString().length()-1).toString());
- writer.close();//一定要關閉,不然可能出現參數不全的錯誤
- sb=null;
- }
- conn.connect();//建立連接
- sb=new StringBuffer();
- //獲取連接狀態碼
- int recode=conn.getResponseCode();
- BufferedReader reader=null;
- if(recode==200){
- //Returns an input stream that reads from this open connection
- //從連接中獲取輸入流
- InputStream in=conn.getInputStream();
- //對輸入流進行封裝
- reader=new BufferedReader(new InputStreamReader(in));
- String str=null;
- sb=new StringBuffer();
- //從輸入流中讀取數據
- while((str=reader.readLine())!=null){
- sb.append(str).append(System.getProperty("line.separator"));
- }
- //關閉輸入流
- reader.close();
- if (sb.toString().length() == 0) {
- return null;
- }
- return sb.toString().substring(0,
- sb.toString().length() - System.getProperty("line.separator").length());
- }
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }finally{
- if(conn!=null)//關閉連接
- conn.disconnect();
- }
- return null;
- }
- }
Demo2:調用獲取城市列表接口示例
- package juheAPI;
- import net.sf.json.JSONArray;
- import net.sf.json.JSONObject;
- /**
- * 獲取城市列表
- * 全國天氣預報接口調用JAVA示例
- * dtype string N 返回數據格式:json或xml,默認json
- * key string Y 你申請的key
- * @author silk
- *
- */
- public class GetCityList {
- /**
- * 調用獲取城市列表接口,返回所有數據
- * @return 返回接口數據
- */
- public static String excute(){
- String url="http://v.juhe.cn/weather/citys?key=***a7558b2e0bedaa19673f74a6809ce";//接口URL
- //PureNetUtil是一個封裝了get和post方法獲取網絡請求數據的工具類
- return PureNetUtil.get(url);//使用get方法
- }
- /**
- * 調用接口返回數據后,解析數據,根據輸入城市名得到對應ID
- * @param cityName 城市名稱
- * @return 返回對應ID
- */
- public static String getIDBycityName(String cityName) {
- String result=excute();//返回接口結果,得到json格式數據
- if(result!=null){
- JSONObject obj=JSONObject.fromObject(result);
- result=obj.getString("resultcode");//得到返回狀態碼
- if(result!=null&&result.equals("200")){//200表示成功返回數據
- result=obj.getString("result");//得到城市列表的json格式字符串數組
- JSONArray arr=JSONArray.fromObject(result);
- for(Object o:arr){//對arr進行遍歷
- //將數組中的一個json個數字符串進行解析
- obj=JSONObject.fromObject(o.toString());
- /*此時obj如 {"id":"2","province":"北京","city":"北京","district":"海淀"}*/
- //以city這個key為線索判斷所需要尋找的這條記錄
- result=obj.getString("district");
- //防止輸入城市名不全,如蘇州市輸入為蘇州,類似與模糊查詢
- if(result.equals(cityName)||result.contains(cityName)){
- result=obj.getString("id");//得到ID
- return result;
- }
- }
- }
- }
- return result;
- }
- public static void main(String[] args) {
- System.out.println(getIDBycityName("香港"));
- }
- }
Demo3:調用根據城市名/id查詢天氣
- package juheAPI;
- import net.sf.json.JSONObject;
- /**
- * 根據城市名/id查詢天氣
- * @author silk
- *
- */
- public class WeatherReportByCity {
- /**
- * 根據城市名獲取
- * @param cityName
- * @return
- */
- public static String excute(String cityName){
- String url=//此處以返回json格式數據示例,所以format=2,以根據城市名稱為例,cityName傳入中文
- "http://v.juhe.cn/weather/index?cityname="+cityName+"&key=***a7558b2e0bedaa19673f74a6809ce";
- return PureNetUtil.get(url);//通過工具類獲取返回數據
- }
- /**
- * 獲取返回數據中的一個屬性示例,此處以獲取今日溫度為例
- * "temperature": "8℃~20℃" 今日溫度
- * @param args
- * @return
- */
- public static String GetTodayTemperatureByCity(String city) {
- String result=excute(city);
- if(result!=null){
- JSONObject obj=JSONObject.fromObject(result);
- /*獲取返回狀態碼*/
- result=obj.getString("resultcode");
- /*如果狀態碼是200說明返回數據成功*/
- if(result!=null&&result.equals("200")){
- result=obj.getString("result");
- //此時result中數據有多個key,可以對其key進行遍歷,得到對個屬性
- obj=JSONObject.fromObject(result);
- //今日溫度對應的key是today
- result=obj.getString("today");
- obj=JSONObject.fromObject(result);
- //今日溫度對應當key是temperature
- result=obj.getString("temperature");
- return result;
- }
- }
- return result;
- }
- public static void main(String[] args) {
- System.out.println(GetTodayTemperatureByCity("蘇州"));
- }
- }
Demo4:調用天氣種類及表示列表接口示例
- package juheAPI;
- import net.sf.json.JSONArray;
- import net.sf.json.JSONObject;
- /**
- * 天氣種類及標識列表接口調用JAVA示例
- * @author silk
- */
- public class GetWeatherSignAndTypeList {
- //接口地址,因為只需要傳入一個固定的key為參數,所以設為常量
- private static final String URL= "http://v.juhe.cn/weather/uni?key=***a7558b2e0bedaa19673f74a6809ce";
- /**
- * 通過工具類獲取數據
- * @return
- */
- public static String excute(){
- return PureNetUtil.get(URL);//調用工具類獲取接口數據
- }
- /**
- * 利用遍歷數組的方式獲取
- * @param wid天氣對應id
- * @return 天氣名稱
- */
- public static String getWeatherByWid(String wid) {
- String result=excute();//獲取接口數據
- if(result!=null){
- JSONObject obj=JSONObject.fromObject(result);
- result=obj.getString("resultcode");
- /*獲取返回狀態碼*/
- if(result!=null&&result.equals("200")){
- /*獲取數組數據*/
- result=obj.getString("result");
- JSONArray arr=JSONArray.fromObject(result);
- for(Object o:arr){//遍歷數組
- obj=JSONObject.fromObject(o.toString());
- //如果遍歷到需要的數據后直接返回結果,根據key(wid)得到value判斷是否等於傳入參數
- if(obj.getString("wid").equals(wid)){
- result=obj.getString("weather");
- return result;
- }
- }
- }
- }
- return result;
- }
- public static void main(String[] args) {
- System.out.println(getWeatherByWid("10"));
- }
- }
step5:調用接口時候如果狀態碼不是200,仔細參考文檔說明,也就是返回step3:看文檔!