一、数据请求
使用http实现网络数据请求,如android开发使用的okhttp、retrofit等。鸿蒙日常开发者,可以使用华为自带的http请求库也可以使用第三方例如axios等执行网络请求。 使用网络请求必须先添加网络权限,在module.json5下面添加,如图所示:
1.使用鸿蒙自带的http请求
1. 导入http模块:
import http from '@ohos.net.http';
2.创建http对象,httpRequest:
let httpRequest = http.createHttp();
3.发起请求Get和Post如下:
// Get 请求
let promise = httpRequest.request(
"url",
{
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
}
)
promise.then((data) => {
// 请求成功
if (data.responseCode == http.ResponseCode.OK) {
// 数据解析
}
}).catch((error) => {
// 异常处理
});
// Post 请求
let promise = httpRequest.request(
"url",
{
method: http.RequestMethod.POST,
extraData: {
// 请求参数
"param": ""
},
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
}
)
promise.then((data) => {
// 请求成功
if (data.responseCode == http.ResponseCode.OK) {
// 数据解析
}
}).catch((error) => {
// 异常处理
});
2.使用第三方请求框架,axios
1.安装axios:
ohpm install @ohos/axios
如果遇到ohpm没有安装,先配置node.js+ohpm环境变量,参考ohpm使用指导
遇到问题ohpm报没有初始化: “ohpm has not been initialized yet. Execute the init script to initialize it first.” 解决方案:完整配置node.js环境变量,然后执行ohpm安装目录bin下面的init脚本,注意脚本获取node.js路径,是否和自己安装的node.js一致。
2.引用axios:
import axios, { FormData } from '@ohos/axios'
3.使用axios发起请求:
// get请求
axios.get("url").then().catch()
// post请求
let form = new FormData()
form.append('name','ceshi')
form.append('password',123)
axios.post("url",form).then().catch()
具体使用axios方法,请参考github