?文章的目的為了記錄使用Arkts?進行Harmony?app?開發學習的經歷。本職為嵌入式軟件開發,公司安排開發app,臨時學習,完成app的開發。開發流程和要點有些記憶模糊,趕緊記錄,防止忘記。
?相關鏈接:
開源 Arkts 鴻蒙應用 開發(一)工程文件分析-CSDN博客
開源 Arkts 鴻蒙應用 開發(二)封裝庫.har制作和應用-CSDN博客
開源 Arkts 鴻蒙應用 開發(三)Arkts的介紹-CSDN博客
開源 Arkts 鴻蒙應用 開發(四)布局和常用控件-CSDN博客
開源 Arkts 鴻蒙應用 開發(五)控件組成和復雜控件-CSDN博客
開源 Arkts 鴻蒙應用 開發(六)數據持久--文件和首選項存儲-CSDN博客
開源 Arkts 鴻蒙應用 開發(七)數據持久--sqlite關系數據庫-CSDN博客
開源 Arkts 鴻蒙應用 開發(八)多媒體--相冊和相機-CSDN博客
開源 Arkts 鴻蒙應用 開發(九)通訊--tcp客戶端-CSDN博客
開源 Arkts 鴻蒙應用 開發(十)通訊--Http-CSDN博客
?推薦鏈接:
開源 java android app 開發(一)開發環境的搭建-CSDN博客
開源 java android app 開發(二)工程文件結構-CSDN博客
開源 java android app 開發(三)GUI界面布局和常用組件-CSDN博客
開源 java android app 開發(四)GUI界面重要組件-CSDN博客
開源 java android app 開發(五)文件和數據庫存儲-CSDN博客
開源 java android app 開發(六)多媒體使用-CSDN博客
開源 java android app 開發(七)通訊之Tcp和Http-CSDN博客
開源 java android app 開發(八)通訊之Mqtt和Ble-CSDN博客
開源 java android app 開發(九)后臺之線程和服務-CSDN博客
開源 java android app 開發(十)廣播機制-CSDN博客
開源 java android app 開發(十一)調試、發布-CSDN博客
開源 java android app 開發(十二)封庫.aar-CSDN博客
推薦鏈接:
開源C# .net mvc 開發(一)WEB搭建_c#部署web程序-CSDN博客
開源 C# .net mvc 開發(二)網站快速搭建_c#網站開發-CSDN博客
開源 C# .net mvc 開發(三)WEB內外網訪問(VS發布、IIS配置網站、花生殼外網穿刺訪問)_c# mvc 域名下不可訪問內網,內網下可以訪問域名-CSDN博客
開源 C# .net mvc 開發(四)工程結構、頁面提交以及顯示_c#工程結構-CSDN博客
https://blog.csdn.net/ajassi2000/article/details/149584283?spm=1011.2124.3001.6209開源 C# .net mvc 開發(五)常用代碼快速開發_c# mvc開發-CSDN博客
本章內容主要是通過Http訪問web網站,獲得天氣的Json數據,進行解析的功能。將訪問的頁面地址進行修改,添加id和key則可以訪問網站的Api,實現高級功能。
一、添加權限,與上個章節相同,在module.json5的最后添加上以下代碼
"requestPermissions": [{"name": "ohos.permission.INTERNET"}]
二、Index.ets代碼分析
2.1? 界面代碼
2個Text,1個顯示Http的返回,1個顯示json數據
以下為代碼
build() {Column() {// 顯示獲取到的網頁內容Scroll() {Column() {Text(this.responseData).fontSize(16).width('100%').textAlign(TextAlign.Start).padding(10)// 添加天氣信息顯示區域if (this.weatherInfo) {Divider().margin(10)Text('解析后的天氣數據:').fontSize(18).fontWeight(FontWeight.Bold).margin({ bottom: 10 })Text(`城市: ${this.weatherInfo.city}`).fontSize(16).margin({ bottom: 5 })Text(`溫度: ${this.weatherInfo.temp}°C`).fontSize(16).margin({ bottom: 5 })Text(`風向: ${this.weatherInfo.WD}`).fontSize(16).margin({ bottom: 5 })Text(`風力: ${this.weatherInfo.WS}`).fontSize(16).margin({ bottom: 5 })Text(`濕度: ${this.weatherInfo.SD}`).fontSize(16).margin({ bottom: 5 })Text(`氣壓: ${this.weatherInfo.qy} hPa`).fontSize(16).margin({ bottom: 5 })Text(`更新時間: ${this.weatherInfo.time}`).fontSize(16).margin({ bottom: 5 })}}.width('100%')}.height('80%').width('100%')// 請求按鈕Button('獲取天氣數據').width('80%').height(50).margin(20).onClick(() => {this.fetchWeatherData();})}.width('100%').height('100%')
2.2? Json數據結構
天氣數據
以下為代碼
// 定義天氣信息的接口類型
interface WeatherInfo {city: string;cityid: string;temp: string;WD: string;WS: string;SD: string;WSE: string;time: string;isRadar: string;Radar: string;njd: string;qy: string;rain: string;
}interface WeatherResponse {weatherinfo: WeatherInfo;
}
2.3??fetchWeatherData()方法:
創建HTTP請求,http.createHttp()
發送GET請求到天氣API,httpRequest.request()
成功時解析JSON并更新UI
以下為代碼
// 發起HTTP請求private fetchWeatherData() {let httpRequest = http.createHttp();this.responseData = '正在請求數據...';this.weatherInfo = null;httpRequest.request('https://www.weather.com.cn/data/sk/101010100.html',{method: http.RequestMethod.GET,header: {'Content-Type': 'application/json'}},(err, data) => {if (err) {this.responseData = `請求失敗: ${JSON.stringify(err)}`;promptAction.showToast({ message: '請求失敗', duration: 2000 });return;}if (data.responseCode === 200) {try {const result: WeatherResponse = JSON.parse(data.result.toString());//this.responseData = `HTTP狀態碼: ${data.responseCode}\n\n原始JSON數據:\n${JSON.stringify(result, null, 2)}`;this.responseData = data.result.toString();if (result.weatherinfo) {this.weatherInfo = result.weatherinfo;}promptAction.showToast({ message: '獲取并解析成功', duration: 2000 });} catch (e) {this.responseData = `JSON解析失敗: ${e.message}\n\n原始數據:\n${data.result}`;promptAction.showToast({ message: 'JSON解析失敗', duration: 2000 });}} else {this.responseData = `請求異常: HTTP狀態碼 ${data.responseCode}`;promptAction.showToast({ message: '請求異常', duration: 2000 });}});}
2.4? 網絡API的使用
網上有各種網絡API,通常的方式是訪問地址和id以及key,通過注冊可以獲得id和key,訪問網址就可以獲得輸入,比如https://xxx/now?&id=CN101010100&key=xxxxx
關鍵流程:創建HTTP實例,?發起GET請求,處理響應(HTTP狀態碼非200為出錯需要處理)
https://www.weather.com.cn/data/sk/101010100.html地址頁面圖片
下面為代碼
import http from '@ohos.net.http';
import promptAction from '@ohos.promptAction';
import webview from '@ohos.web.webview';// 定義天氣信息的接口類型
interface WeatherInfo {city: string;cityid: string;temp: string;WD: string;WS: string;SD: string;WSE: string;time: string;isRadar: string;Radar: string;njd: string;qy: string;rain: string;
}interface WeatherResponse {weatherinfo: WeatherInfo;
}@Entry
@Component
struct HttpExample {@State responseData: string = '等待獲取數據...';@State webController: webview.WebviewController = new webview.WebviewController();@State weatherInfo: WeatherInfo | null = null;build() {Column() {// 顯示獲取到的網頁內容Scroll() {Column() {Text(this.responseData).fontSize(16).width('100%').textAlign(TextAlign.Start).padding(10)// 添加天氣信息顯示區域if (this.weatherInfo) {Divider().margin(10)Text('解析后的天氣數據:').fontSize(18).fontWeight(FontWeight.Bold).margin({ bottom: 10 })Text(`城市: ${this.weatherInfo.city}`).fontSize(16).margin({ bottom: 5 })Text(`溫度: ${this.weatherInfo.temp}°C`).fontSize(16).margin({ bottom: 5 })Text(`風向: ${this.weatherInfo.WD}`).fontSize(16).margin({ bottom: 5 })Text(`風力: ${this.weatherInfo.WS}`).fontSize(16).margin({ bottom: 5 })Text(`濕度: ${this.weatherInfo.SD}`).fontSize(16).margin({ bottom: 5 })Text(`氣壓: ${this.weatherInfo.qy} hPa`).fontSize(16).margin({ bottom: 5 })Text(`更新時間: ${this.weatherInfo.time}`).fontSize(16).margin({ bottom: 5 })}}.width('100%')}.height('80%').width('100%')// 請求按鈕Button('獲取天氣數據').width('80%').height(50).margin(20).onClick(() => {this.fetchWeatherData();})}.width('100%').height('100%')}// 發起HTTP請求private fetchWeatherData() {let httpRequest = http.createHttp();this.responseData = '正在請求數據...';this.weatherInfo = null;httpRequest.request('https://www.weather.com.cn/data/sk/101010100.html',{method: http.RequestMethod.GET,header: {'Content-Type': 'application/json'}},(err, data) => {if (err) {this.responseData = `請求失敗: ${JSON.stringify(err)}`;promptAction.showToast({ message: '請求失敗', duration: 2000 });return;}if (data.responseCode === 200) {try {const result: WeatherResponse = JSON.parse(data.result.toString());//this.responseData = `HTTP狀態碼: ${data.responseCode}\n\n原始JSON數據:\n${JSON.stringify(result, null, 2)}`;this.responseData = data.result.toString();if (result.weatherinfo) {this.weatherInfo = result.weatherinfo;}promptAction.showToast({ message: '獲取并解析成功', duration: 2000 });} catch (e) {this.responseData = `JSON解析失敗: ${e.message}\n\n原始數據:\n${data.result}`;promptAction.showToast({ message: 'JSON解析失敗', duration: 2000 });}} else {this.responseData = `請求異常: HTTP狀態碼 ${data.responseCode}`;promptAction.showToast({ message: '請求異常', duration: 2000 });}});}
}
三、最終效果
?