HarmonyOS ArkUI之開發(fā)基礎(chǔ)(網(wǎng)絡(luò)請求)
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)
簡介
前段時間一直研究ArkUI中的聲明式開發(fā),開發(fā)了一些demo,但都是界面相關(guān)的,相對來說比較基礎(chǔ),也比較簡單。所以研究一下其他的,現(xiàn)在成熟的APP都會有網(wǎng)絡(luò)交互,所以記錄一篇網(wǎng)絡(luò)請求相關(guān)的。
本項(xiàng)目界面搭建基于ArkUI中TS擴(kuò)展的聲明式開發(fā)范式,關(guān)于語法和概念直接看官網(wǎng)官方文檔地址:
基于TS擴(kuò)展的聲明式開發(fā)范式1、基于TS擴(kuò)展的聲明式開發(fā)范式2
本文介紹開發(fā)基礎(chǔ)知識(網(wǎng)絡(luò)請求):
數(shù)據(jù)接口:聚合免費(fèi)API(天氣預(yù)報(bào))
網(wǎng)絡(luò)請求:ArkUI自帶的網(wǎng)絡(luò)請求
效果演示


開發(fā)步驟
1、聲明網(wǎng)絡(luò)請求權(quán)限
在 entry 下的 config.json 中 module 字段下配置權(quán)限
- "reqPermissions": [
- {
- "name": "ohos.permission.INTERNET"
- }
- ]
2、支持http明文請求
默認(rèn)支持https,如果要支持http,在 entry 下的 config.json 中 deviceConfig 字段下配置
- "default": {
- "network": {
- "cleartextTraffic": true
- }
- }
3、創(chuàng)建HttpRequest
- // 導(dǎo)入模塊
- import http from '@ohos.net.http';
- // 創(chuàng)建HttpRequest對象
- let httpRequest = http.createHttp();
4、發(fā)起請求
GET請求(默認(rèn)為GET請求)
- // 請求方式:GET
- getRequest() {
- // 每一個httpRequest對應(yīng)一個http請求任務(wù),不可復(fù)用
- let httpRequest = http.createHttp()
- let url = 'http://apis.juhe.cn/simpleWeather/query?key=397c9db4cb0621ad0313123dab416668&city=北京'
- httpRequest.request(url, (err, data) => {
- // 處理數(shù)據(jù)
- })
- }
POST請求
目前發(fā)現(xiàn)API的BUG:看官方文檔method可以設(shè)置為字符串,從源碼得知method的類型為:RequestMethod,但是設(shè)置 method: http.RequestMethod.POST 請求數(shù)據(jù)報(bào)錯,設(shè)置成 method: http.POST 可以
- // 請求方式:POST
- postRequest() {
- // 每一個httpRequest對應(yīng)一個http請求任務(wù),不可復(fù)用
- let httpRequest = http.createHttp()
- let url = 'http://apis.juhe.cn/simpleWeather/query'
- httpRequest.request(url,
- {
- // 看源碼得知method的類型為:RequestMethod
- // 但是設(shè)置 method: http.RequestMethod.POST 報(bào)錯
- // 設(shè)置成 method: http.POST 可以
- method: http.POST,
- extraData: {
- 'key': '397c9db4cb0621ad0313123dab416668',
- 'city': '北京'
- }
- },
- (err, data) => {
- // 處理數(shù)據(jù)
- })
- }
5、解析數(shù)據(jù)(簡單示例)
(1)網(wǎng)絡(luò)請求到的json字符串
- {
- "name":"梁迪迪",
- "age":"26",
- "sex":"男"
- }
(2)創(chuàng)建相應(yīng)的對象
- class User {
- name: string // 姓名
- age: string // 年齡
- sex: string // 性別
- }
(3)解析數(shù)據(jù)
- // 請求方式:GET
- getRequest() {
- // 每一個httpRequest對應(yīng)一個http請求任務(wù),不可復(fù)用
- let httpRequest = http.createHttp()
- let url = ''
- httpRequest.request(url, (err, data) => {
- // 處理數(shù)據(jù)
- if (!err) {
- if (data.responseCode == 200) {
- // 解析數(shù)據(jù)
- var user: User = JSON.parse(JSON.stringify(data.result))
- }
- }
- })
- }
51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)