介绍
基于鸿蒙API version 9 请求接口前置封装
1. 配置文件entry/src/ohosTest/modele.json5 允许请求网络
{
"module": {
"name": "entry_test",
"type": "feature",
"description": "$string:module_test_desc",
"mainElement": "TestAbility",
"deviceTypes": [
"phone",
"tablet"
],
"deliveryWithInstall": true,
"installationFree": false,
"pages": "$profile:test_pages",
"abilities": [
{
"name": "TestAbility",
"srcEntry": "./ets/testability/TestAbility.ets",
"description": "$string:TestAbility_desc",
"icon": "$media:icon",
"label": "$string:TestAbility_label",
"exported": true,
"startWindowIcon": "$media:icon",
"startWindowBackground": "$color:start_window_background",
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
]
}
]
}
],
// 开启网络请求
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
2.request.ets请求拦截文件
import http from '@ohos.net.http'//引入http
import PreferencesUtil from '../PreferencesUtil/Index'//存储用户信息
type ApiRes = {
code: string
data: any
msg: string
}
let userInfo:string;
async function getUserInfo() {
userInfo= await PreferencesUtil.getUserInfo()
}
const BASEURL = ''//baseUrl
let HEADER={
APPID:"",
CLIENT:'',
OPENKEY:'',
USERID:'',// (根据接口需要,这里的userId相当于token)
}//请求头信息 (根据接口需要)
export const request =({
url,
method = http.RequestMethod.GET,
extraData = {},
header = {}}): Promise<ApiRes> => {
// 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp()
return new Promise((resolve, reject) => {
//从Preferences中获取userInfo用户信息Preferences是异步
getUserInfo().then(()=>{
if(userInfo){
HEADER.USERID=JSON.parse(userInfo)['userId']
}else{
HEADER.USERID=''
}
httpRequest.request(
// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定
`${BASEURL}${url}`,
{
method, // 可选,默认为http.RequestMethod.GET
//请求头 可以通过传参的形式补充
header:{
header,
...HEADER
},
// 当使用POST请求时此字段用于传递内容
extraData,
expectDataType: http.HttpDataType.OBJECT,
connectTimeout: 60000,//连接超时时间
readTimeout: 60000,//读取超时时间
},
(err, data) => {
if (!err) {
// 取消订阅HTTP响应头事件
// httpRequest.off('headersReceive');
// 当该请求使用完毕时,调用destroy方法主动销毁
httpRequest.destroy()
// data.result为HTTP响应内容,可根据业务需要进行解析
resolve(data.result as ApiRes)
} else {
reject(err)
// 取消订阅HTTP响应头事件
// httpRequest.off('headersReceive')
// 当该请求使用完毕时,调用destroy方法主动销毁。
httpRequest.destroy()
}
}
)
})
})
}
3.PreferencesUtil.ets文件 用于储存用户信息
import dataPreferences from '@ohos.data.preferences'
const PREFERENCES_NAME = 'myPreferences' // 首选项名字
const USERINFO = 'USERINFO' // 首选项Key字段
export default class PreferencesUtil {
static preferences = null
// 创建dataPreferences
static async createPreferences(context) {
// 获取首选项实例
this.preferences = await dataPreferences.getPreferences(
context,
PREFERENCES_NAME
)
}
// 保存userInfo
static saveUserInfo(userInfoRes: string) {
// 保存数据
this.preferences.put(USERINFO, userInfoRes)
//写入文件深度存储
this.preferences.flush()
}
// 获取userInfo
static async getUserInfo() {
return this.preferences.get(USERINFO, '')
}
//删除userInfo
static async delUserInfo() {
this.preferences.delete(USERINFO,'')
}
}
3.1使用preferences需要在入口文件ets/entryability/EntryaBility.ets文件中创建
import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import PreferencesUtil from '../common/utils/PreferencesUtil/Index'
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
//创建实例
PreferencesUtil.createPreferences(this.context)
}
api文件
import { request } from '../request/Index'//引入请求拦截
import http from '@ohos.net.http'
//POST请求 登录接口
export const login = (extraData: { uname: string; pword: string }) => {
return request({
url: '登录url',
method: http.RequestMethod.POST,
extraData,
})
}
//GTE请求 关注接口
export const follow= (extraData: { celeId: number; type: number }) => {
return request({
url: '关注url',
method: http.RequestMethod.GET,
extraData,
})
}
使用页面Index.ets
import { login,follow} from '../common/utils/api/User'
import PreferencesUtil from '../common/utils/PreferencesUtil/Index'
@Entry
@Component
struct Index {
// 登录接口
async loginFn() {
const res = await login({
uname:'123456',
pword: '123456'
})
//储存登录信息
PreferencesUtil.saveUserInfo(JSON.stringify((res.data)))
}
//关注接口
async followFn(){
const resData = await follow({
celeId:1,
type:1
})
console.log(JSON.stringify(resData))
}
build() {
Row() {
Column() {
Button('登录',{ type: ButtonType.Normal, stateEffect: true }).borderRadius('12lpx')
.backgroundColor('#FD6E6F')
.width('100%')
.height('60')
.onClick(()=>{
this.loginFn()
})
Button('获取用户信息',{ type: ButtonType.Normal, stateEffect: true }).borderRadius('12lpx')
.backgroundColor('#FD6E6F')
.width('100%')
.height('60')
.margin(10)
.onClick(async ()=>{
//获取用户信息
const info = await PreferencesUtil.getUserInfo()
console.log(info)
})
Button('取消关注',{ type: ButtonType.Normal, stateEffect: true }).borderRadius('12lpx')
.backgroundColor('#FD6E6F')
.width('100%')
.height('60')
.margin(10)
.onClick(async ()=>{
//点击关注
this.followFn()
})
Button('清除用户信息',{ type: ButtonType.Normal, stateEffect: true }).borderRadius('12lpx')
.backgroundColor('#FD6E6F')
.width('100%')
.height('60')
.margin(10)
.onClick(async ()=>{
//清除用户信息
await PreferencesUtil.delUserInfo()
})
}
.width('100%')
}
.height('100%')
}
}