简介
前段时间一直研究ArkUI中的声明式开发,开发了一些demo,但都是界面相关的,相对来说比较基础,也比较简单。所以研究一下其他的,现在成熟的APP都会有网络交互,所以记录一篇网络请求相关的。
本项目界面搭建基于ArkUI中TS扩展的声明式开发范式,关于语法和概念直接看官网官方文档地址:
基于TS扩展的声明式开发范式1、基于TS扩展的声明式开发范式2
本文介绍开发基础知识(网络请求):
数据接口:聚合免费API(天气预报)
网络请求:ArkUI自带的网络请求
效果演示


开发步骤
1、声明网络请求权限
在 entry 下的 config.json 中 module 字段下配置权限
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
- 1.
- 2.
- 3.
- 4.
- 5.
2、支持http明文请求
默认支持https,如果要支持http,在 entry 下的 config.json 中 deviceConfig 字段下配置
"default": {
"network": {
"cleartextTraffic": true
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
3、创建HttpRequest
// 导入模块
import http from '@ohos.net.http';
// 创建HttpRequest对象
let httpRequest = http.createHttp();
- 1.
- 2.
- 3.
- 4.
4、发起请求
GET请求(默认为GET请求)
// 请求方式:GET
getRequest() {
// 每一个httpRequest对应一个http请求任务,不可复用
let httpRequest = http.createHttp()
let url = 'http://apis.juhe.cn/simpleWeather/query?key=397c9db4cb0621ad0313123dab416668&city=北京'
httpRequest.request(url, (err, data) => {
// 处理数据
})
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
POST请求
目前发现API的BUG:看官方文档method可以设置为字符串,从源码得知method的类型为:RequestMethod,但是设置 method: http.RequestMethod.POST 请求数据报错,设置成 method: http.POST 可以
// 请求方式:POST
postRequest() {
// 每一个httpRequest对应一个http请求任务,不可复用
let httpRequest = http.createHttp()
let url = 'http://apis.juhe.cn/simpleWeather/query'
httpRequest.request(url,
{
// 看源码得知method的类型为:RequestMethod
// 但是设置 method: http.RequestMethod.POST 报错
// 设置成 method: http.POST 可以
method: http.POST,
extraData: {
'key': '397c9db4cb0621ad0313123dab416668',
'city': '北京'
}
},
(err, data) => {
// 处理数据
})
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
5、解析数据(简单示例)
(1)网络请求到的json字符串
{
"name":"梁迪迪",
"age":"26",
"sex":"男"
}
- 1.
- 2.
- 3.
- 4.
- 5.
(2)创建相应的对象
class User {
name: string // 姓名
age: string // 年龄
sex: string // 性别
}
- 1.
- 2.
- 3.
- 4.
- 5.
(3)解析数据
// 请求方式:GET
getRequest() {
// 每一个httpRequest对应一个http请求任务,不可复用
let httpRequest = http.createHttp()
let url = ''
httpRequest.request(url, (err, data) => {
// 处理数据
if (!err) {
if (data.responseCode == 200) {
// 解析数据
var user: User = JSON.parse(JSON.stringify(data.result))
}
}
})
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.