Android开发之和风天气篇:1、获取天气信息
生活随笔
收集整理的這篇文章主要介紹了
Android开发之和风天气篇:1、获取天气信息
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
TIME:2020年7月6日
:1、獲取天氣信息
- 和風天氣API使用方法:
- step1 申請天氣接口
- step2 天氣接口初始化
- step3 選擇服務模式
- step4 通過URL請求數據
- step5解析JSON數據
- 附上源碼:
和風天氣API使用方法:
1、申請天氣接口
2、天氣接口賬號初始化
3、選擇服務模式,免費還是商業版
4、通過URL請求數據(get和post方式)并接收數據
5、解析JSON數據
step1 申請天氣接口
天氣接口申請
step2 天氣接口初始化
HeConfig.init(publicId,key);step3 選擇服務模式
//切換到免費服務模式HeConfig.switchToFreeServerNode();step4 通過URL請求數據
private void queryWeather() {new Thread() {@Overridepublic void run() {String param = "key=07a717828d9f49169062e88e66d50697&location=auto_ip";StringBuilder sb = new StringBuilder();InputStream is = null;BufferedReader br = null;PrintWriter out = null;try {String url = "https://free-api.heweather.net/s6/weather";URL uri = new URL(url);HttpURLConnection connection = (HttpURLConnection) uri.openConnection();//開啟一個url的連接,用HttpURLConnection連接方式處理connection.setRequestMethod("POST");//設置連接對象的請求數據的方式connection.setConnectTimeout(3000);//設置連接對象的請求超時的時間connection.setReadTimeout(5000);//設置讀超時connection.setRequestProperty("accept", "*/*");//發送參數connection.setDoOutput(true);out = new PrintWriter(connection.getOutputStream());out.print(param);Log.e("param",param);out.flush();//接收結果is = connection.getInputStream();br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//緩沖逐行讀取String line;while ( ( line = br.readLine() ) != null ) {sb.append(line);}queryWeather2();Log.e("success","tmp:" + sb.toString());} catch (Exception ignored) {} finally {//關閉流try {if(is!=null){is.close();}if(br!=null){br.close();}if (out!=null){out.close();}} catch ( Exception ignored ) {}}}}.start();}step5解析JSON數據
以實況天氣為例
public void queryWeather2() {/*** 實況天氣* 實況天氣即為當前時間點的天氣狀況以及溫濕風壓等氣象指數,具體包含的數據:體感溫度、* 實測溫度、天氣狀況、風力、風速、風向、相對濕度、大氣壓強、降水量、能見度等。** @param context 上下文* @param location 地址詳解* @param lang 多語言,默認為簡體中文,海外城市默認為英文* @param unit 單位選擇,公制(m)或英制(i),默認為公制單位* @param listener 網絡訪問回調接口*/HeWeather.getWeatherNow(Weather.this, "CN101080101",Lang.CHINESE_SIMPLIFIED, Unit.METRIC, new HeWeather.OnResultWeatherNowBeanListener() {@Overridepublic void onError(Throwable e) {Log.i(TAG, "Weather Now onError: ", e);}@Overridepublic void onSuccess(Now dataObject) {Log.i(TAG, " Weather Now onSuccess: " + new Gson().toJson(dataObject));//先判斷返回的status是否正確,當status正確時獲取數據,若status不正確,可查看status對應的Code值找到原因if (Code.OK.getCode().equalsIgnoreCase(dataObject.getStatus())) {//此時返回數據Basic basic = dataObject.getBasic();String location = basic.getLocation();NowBase now = dataObject.getNow();String tmp = now.getTmp();Intent intent = new Intent();intent.putExtra("tmp", tmp);intent.setAction("number_tmp");sendBroadcast(intent);} else {//在此查看返回數據失敗的原因String status = dataObject.getStatus();Code code = Code.toEnum(status);Log.i(TAG, "failed code: " + code);}}});}附上源碼:
下載地址
總結
以上是生活随笔為你收集整理的Android开发之和风天气篇:1、获取天气信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Google Dremel 原理 - 如
- 下一篇: Android开发之高德API篇:2、高