本文來自AppInventor2中文網(www.fun123.cn)參考文檔,調用第三方天氣接口獲取天氣JSON數據,解析并展示在App上。
App效果圖,展示未來7日的天氣預報,包括日期、天氣圖示和溫度:
App原理介紹
通過調用第三方天氣api,填入必要的參數,通過Web客戶端請求url。返回json格式的數據結果,使用AppInventor2解析json結果,顯示到App上即可。
第三方天氣API介紹
第三方天氣的api平臺特別多,這里僅以“和風天氣”(dev.qweather.com
)作為演示,其他平臺的使用方法都是幾乎一樣的。
平臺的注冊及登錄步驟請自行完成,登錄后需要創建一個項目以獲得API調用時必要的用戶認證key
。
創建一個項目
填寫必要的參數
查看已創建的項目
這時,我們就能得到了用戶認證key
,后續步驟會用到這個關鍵的數據。
查看API文檔,確定我們需要準備的數據
通過文檔可知,我們需要在url中替換填入自己的key
。
請求示例:北京7天預報
curl -L -X GET --compressed 'https://api.qweather.com/v7/weather/7d?location=101010100&key=YOUR_KEY'
第三方API的調用
使用”Web客戶端“組件調用第三方API,代碼如下:
JSON結果的解析
請求成功返回JSON示例
{"code": "200","updateTime": "2021-11-15T16:35+08:00","fxLink": "http://hfx.link/2ax1","daily": [{"fxDate": "2021-11-15","sunrise": "06:58","sunset": "16:59","moonrise": "15:16","moonset": "03:40","moonPhase": "盈凸月","moonPhaseIcon": "803","tempMax": "12","tempMin": "-1","iconDay": "101","textDay": "多云","iconNight": "150","textNight": "晴","wind360Day": "45","windDirDay": "東北風","windScaleDay": "1-2","windSpeedDay": "3","wind360Night": "0","windDirNight": "北風","windScaleNight": "1-2","windSpeedNight": "3","humidity": "65","precip": "0.0","pressure": "1020","vis": "25","cloud": "4","uvIndex": "3"},{"fxDate": "2021-11-16","sunrise": "07:00","sunset": "16:58","moonrise": "15:38","moonset": "04:40","moonPhase": "盈凸月","moonPhaseIcon": "803","tempMax": "13","tempMin": "0","iconDay": "100","textDay": "晴","iconNight": "101","textNight": "多云","wind360Day": "225","windDirDay": "西南風","windScaleDay": "1-2","windSpeedDay": "3","wind360Night": "225","windDirNight": "西南風","windScaleNight": "1-2","windSpeedNight": "3","humidity": "74","precip": "0.0","pressure": "1016","vis": "25","cloud": "1","uvIndex": "3"},{"fxDate": "2021-11-17","sunrise": "07:01","sunset": "16:57","moonrise": "16:01","moonset": "05:41","moonPhase": "盈凸月","moonPhaseIcon": "803","tempMax": "13","tempMin": "0","iconDay": "100","textDay": "晴","iconNight": "150","textNight": "晴","wind360Day": "225","windDirDay": "西南風","windScaleDay": "1-2","windSpeedDay": "3","wind360Night": "225","windDirNight": "西南風","windScaleNight": "1-2","windSpeedNight": "3","humidity": "56","precip": "0.0","pressure": "1009","vis": "25","cloud": "0","uvIndex": "3"}],"refer": {"sources": ["QWeather","NMC","ECMWF"],"license": ["QWeather Developers License"]}
}
JSON解析參考代碼
aia源碼
App Inventor 2 天氣預報App開發 - 第三方API接入的通用方法 · App Inventor 2 中文網