网络连接http
http协议是客户端与后端服务器的单方向通信,客户端向服务器发起请求,服务器响应请求。
http的使用
使用该功能需要申请ohos.permission.INTERNET权限。
引入头文件 import http from '@ohos.net.http'
// 每一个httpRequest对应一个HTTP请求任务,不可复用(只能发送一次请求)
let httpRequest = http.createHttp(); //创建一个http的请求任务
httpRequest.request(
'http://localhost:3000/users', //请求的url路径
{ //请求选项HttpRequestOptions
method:http.RequestMethod.GET,
//该http请求类型。
//常用类型GET(获取对应页面数据),POST(向页面提交表单),PUT(修改替换页面数据),
//DELETE(删除页面数据)
//该http请求携带的参数
extraData:{'param1':'value'} //object类型
或 "k1=5&k2=4" //string类型
}
) //返回值为Promise类型:用于存放未来会完成的结果
.then((resp:http.HttpResponse)=>{
if(resp.responseCode==200)
{
//请求成功
}
})
.catch((err:Error)=>{
// 请求失败
})
HttpRequestOptions 与 HttpResponse 参数
GET请求实例
import http from '@ohos.net.http'
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
//GET网络请求函数
getUserName(){
let httpRequest = http.createHttp()
let url = 'XXX';
httpRequest.request(url,{//设置请求报文的参数
method: http.RequestMethod.GET, //以GET方式请求
connectTimeout:10000, //连接超时时间ms
readTimeout:10000//读取超时时间ms
},(err,data)=>{//回调函数返回数据
//通过控制台查看返回的数据
console.info("data:" + JSON.stringify(data.result))
console.info("data:" + JSON.stringify(data.responseCode))
console.info("data:" + JSON.stringify(err))
if(err){
this.message = JSON.stringify(err) //将错误信息显示
}
else {
if(data.responseCode == 200){ //请求有效将用户名称显示
//(返回结果在结构体接收返回值的变量名.result中)
this.message = JSON.parse(data.result.toString()).data.name
}
else { //无效请求则将状态码显示
this.message = data.responseCode + '40'
}
}
})
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
//手动点击发送GET网络请求
Button('发送请求').onClick(()=>{
this.getUserName()
})
}
.width('100%')
}
.height('100%')
}
}
POST请求实例
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
let url = 'XXX'; //准备你要请求的url地址
let requestOptions = { //设置请求报文的参数
method: http.RequestMethod.POST, //以POST方式请求
header:{
'Content - Type':'application/json'
},
extraData: {//发送额外的参数
"data": "data to send",
},
connectTimeout:10000, //连接超时时间ms
readTimeout:10000//读取超时时间ms
}
//调用on()方法订阅响应头
httpRequest.on( 'headersReceive',(header) => {
console.info( 'header:'+ JSON.stringify(header));});
//调用request()方法向对方发送请求报文
let res = httpRequest.request(url, requestOptions);
//通过Promise方式处理响应,返回到控制台
res.then((data) =>{
console.info('header:'+ JSON.stringify(data.header));
console.info('Content - Type:' + data.header['Content - Type']);
console.info('Result:'+ data.result);
console.info('code:'+ data.responseCode);
}).catch((err) =>{
//处理请求异常信息并销毁请求
console.info('error:'+ JSON.stringify(err));
httpRequest.destroy( );
});
数据持久化
用户首选项
用户首选项(Preference)为应用提供key-value键值型的数据处理能力,支持应用持久化轻量级数据。
要求:
- key为string类型,要求非空且长度不超过80字节
- value可以是string、number、boolean及以上类型数组,大小不超过8192字节
- 数据量建议不超过一万条
首选项的使用
导入头文件:import dataPreference from '@ohos.data.preferences'
获取首选项实例:
prfmap:Map<string,preferences.Preferences>=new Map()
//自定义一个字典,用于存放所有实例
dataPreference.getPreferences(this.context,"实例名")
.then((preferences)=>{ //this.context : UIability 上下文
//获取首选项实例成功
this.prfmap.set("实例名",preferences)
})
.catch((reason)=>{
//获取实例失败
})
数据操作:
//写入数据,如果已经存在则会覆盖,可利用.has()判断是否存在
preferences.put("key",val) //参数:key和value
.then(()=> {preferences.flush()} ) //将实例内容刷新到磁盘上(永久存储)
.catch(()=>{}) //处理异常
//删除数据
preferences.delete('key')
.then(()=>{})
.catch((reason)=>{})
//读取数据
preferences.get('key','默认值') //若未查询到对应关键字,就会返回默认值
.then((value)=>{
console.log("查询成功")
})
.catch((reason)=>{
console.log("查询失败")
})
加载实例----在该UIability的初始化文件中的onCreate()里加载
关键字async 代表这是一个异步函数, 关键字await 表示必须等待后面这条语句执行完才会继续向下执行。await只能在 异步函数中使用 ,关于异步函数概念可以参考下面这篇文章—异步函数详解
为页面属性赋值----在页面渲染aboutToAppear()中赋值
关系型数据库
Harmony OS的关系型数据库:是基于SQLite的本地数据库。
关系型数据库的使用
导入头文件:import relationalStore from '@ohos.relationalStore'
创建数据库,建表:
//rdb配置
const config={
name:'MyStore.db', //数据库文件名
securityLevel:relationStore.SecurityLevel.S1
//数据库安全级别
}
//建表SQL语句
const sql='CREATE TABLE IF NOT EXISTS TASK(
ID INTEGER PRIMARY KEY,
NAME TEXT NOT NULL,
FINISHED bit
)' //sql语句,bit代表boolean
//获取rdb
relationalStore.getRdbStore(this.context,config,(err,rdbStore)=>{
//执行Sql,后续的所有增删查改都是使用rdbStore对象
rdbStore.executeSql(sql) //建表
})
插入数据:
//准备数据
let task={id:1, name:"任务名", finished:false}
//执行新增
this.rdbStore.insert("表名",task)
修改数据:
//要更新的数据
let task = {'finished':true}
//查询条件,RdbPredicates就是条件谓词-----while
let predicates = new relationalStore.RdbPredicates("表名")
predicates.equalTo('ID',id) //while('ID'==id)
//若没有上面这一句,就代表查询所有。
//执行更新
this.rdbStore.update(task,predicates)
删除数据:
//查询条件,RdbPredicates就是条件谓词-----while
let predicates = new relationalStore.RdbPredicates("表名")
predicates.equalTo('ID',id) //while('ID'==id)
//若没有上面这一句,就代表查询所有。
//执行删除
this.rdbStore.delete(predicates)
查询数据:
//查询条件,RdbPredicates就是条件谓词-----while
let predicates = new relationalStore.RdbPredicates("表名")
//执行查询
let result= await this.rdbStore.query(predicates,
['ID','NAME','FINISHED']) //这是个异步函数
//第二个参数表示要查询的字段名
//result 是一个结果集,因此想要获得对应数据,就需要解析
//解析结果
let tasks:any[] = [] //准备数组保存所有查询到的结果
//循环遍历结果集,判断是否已经到了最后一行
while(!result.isAtLastRow)
{
//指针移动到下一行数据(指针初始位置在第一行的前面一行)
result.goToNextRow()
//根据字段名获取字段,从而获取字段值
let id = result.getLong(result.getColumnIndex('ID'));
let name=result.getString(result.getColumnIndex('NAME'));
tasks.push({id,name}) //将数据存入数组
}
boolean类型的数据在数据库中存储为0和1