import http from '@ohos.net.http'
// GET 请求
async function fetchData(url: string): Promise<ResponseData> {
const httpRequest = http.createHttp()
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.GET,
header: { 'Content-Type': 'application/json' },
connectTimeout: 60000,
readTimeout: 60000,
extraData: {} // GET请求通常不需要
})
if (response.responseCode === 200) {
const result = JSON.parse(response.result as string) as ResponseData
return result
} else {
throw new Error(`HTTP Error: ${response.responseCode}`)
}
} finally {
httpRequest.destroy() // 必须销毁请求对象
}
}
// POST 请求
async function postData(url: string, body: Object): Promise<ResponseData> {
const httpRequest = http.createHttp()
try {
const response = await httpRequest.request(url, {
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${getToken()}`
},
extraData: JSON.stringify(body)
})
return JSON.parse(response.result as string) as ResponseData
} finally {
httpRequest.destroy()
}
}
// PUT / DELETE 请求类似,修改 method 即可const httpRequest = http.createHttp()
httpRequest.on('headerReceive', (err, header) => {
console.info('收到响应头')
})
httpRequest.on('dataReceive', (data) => {
console.info('收到数据片段')
})
httpRequest.on('dataEnd', () => {
console.info('数据接收完毕')
})
httpRequest.on('responseReceive', (response) => {
console.info('完整响应')
})
// 流式接收(大文件)
httpRequest.requestInStream(url, options)
// 取消请求
httpRequest.destroy()import http from '@ohos.net.http'
const BASE_URL = 'https://api.example.com'
interface ApiResponse<T> {
code: number
message: string
data: T
}
class HttpClient {
private static instance: HttpClient
private token: string = ''
static getInstance(): HttpClient {
if (!HttpClient.instance) {
HttpClient.instance = new HttpClient()
}
return HttpClient.instance
}
setToken(token: string) {
this.token = token
}
private getHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json'
}
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`
}
return headers
}
async get<T>(path: string, params?: Record<string, string>): Promise<ApiResponse<T>> {
let url = `${BASE_URL}${path}`
if (params) {
const query = Object.entries(params)
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&')
url += `?${query}`
}
return this.request<T>(url, http.RequestMethod.GET)
}
async post<T>(path: string, body?: Object): Promise<ApiResponse<T>> {
const url = `${BASE_URL}${path}`
return this.request<T>(url, http.RequestMethod.POST, body)
}
async put<T>(path: string, body?: Object): Promise<ApiResponse<T>> {
const url = `${BASE_URL}${path}`
return this.request<T>(url, http.RequestMethod.PUT, body)
}
async delete<T>(path: string): Promise<ApiResponse<T>> {
const url = `${BASE_URL}${path}`
return this.request<T>(url, http.RequestMethod.DELETE)
}
private async request<T>(
url: string,
method: http.RequestMethod,
body?: Object
): Promise<ApiResponse<T>> {
const httpRequest = http.createHttp()
try {
const response = await httpRequest.request(url, {
method,
header: this.getHeaders(),
connectTimeout: 30000,
readTimeout: 30000,
extraData: body ? JSON.stringify(body) : undefined
})
if (response.responseCode === 200) {
return JSON.parse(response.result as string) as ApiResponse<T>
}
if (response.responseCode === 401) {
// Token 过期处理
this.handleAuthError()
throw new Error('认证过期')
}
throw new Error(`请求失败: ${response.responseCode}`)
} catch (error) {
console.error(`HTTP Error: ${error}`)
throw error
} finally {
httpRequest.destroy()
}
}
private handleAuthError() {
this.token = ''
// 跳转登录页或刷新token
}
}
export default HttpClient.getInstance()import preferences from '@ohos.data.preferences'
const PREFERENCES_NAME = 'my_app_prefs'
async function getPreferences(context: Context): Promise<preferences.Preferences> {
return preferences.getPreferences(context, PREFERENCES_NAME)
}
// 写入
async function saveSetting(context: Context, key: string, value: preferences.ValueType) {
const prefs = await getPreferences(context)
await prefs.put(key, value)
await prefs.flush() // 持久化到磁盘
}
// 读取
async function getSetting(context: Context, key: string): Promise<preferences.ValueType> {
const prefs = await getPreferences(context)
return prefs.get(key, '') // 默认值
}
// 删除
async function removeSetting(context: Context, key: string) {
const prefs = await getPreferences(context)
await prefs.delete(key)
await prefs.flush()
}
// 清空
async function clearSettings(context: Context) {
const prefs = await getPreferences(context)
await prefs.clear()
await prefs.flush()
}
// 常用存储场景
// saveSetting(context, 'user_token', 'xxx')
// saveSetting(context, 'is_first_launch', true)
// saveSetting(context, 'last_login_time', 1700000000)import relationalStore from '@ohos.data.relationalStore'
const STORE_CONFIG: relationalStore.StoreConfig = {
name: 'app_database.db',
securityLevel: relationalStore.SecurityLevel.S1
}
// 建表
const CREATE_TABLE_SQL = `
CREATE TABLE IF NOT EXISTS user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER,
created_at INTEGER
)
`
async function initDB(context: Context): Promise<relationalStore.RdbStore> {
const store = await relationalStore.getRdbStore(context, STORE_CONFIG)
await store.executeSql(CREATE_TABLE_SQL)
return store
}
// 插入数据
async function insertUser(store: relationalStore.RdbStore, user: User): Promise<number> {
const valueBucket: relationalStore.ValuesBucket = {
'name': user.name,
'age': user.age,
'created_at': Date.now()
}
return store.insert('user', valueBucket)
}
// 查询数据
async function queryUsers(store: relationalStore.RdbStore, ageFilter?: number): Promise<User[]> {
const predicates = new relationalStore.RdbPredicates('user')
if (ageFilter) {
predicates.equalTo('age', ageFilter)
}
predicates.orderByDesc('created_at')
const resultSet = await store.query(predicates)
const users: User[] = []
while (resultSet.goToNextRow()) {
users.push({
id: resultSet.getLong(resultSet.getColumnIndex('id')),
name: resultSet.getString(resultSet.getColumnIndex('name')),
age: resultSet.getLong(resultSet.getColumnIndex('age')),
created_at: resultSet.getLong(resultSet.getColumnIndex('created_at'))
})
}
resultSet.close()
return users
}
// 更新数据
async function updateUser(store: relationalStore.RdbStore, id: number, name: string): Promise<number> {
const valueBucket: relationalStore.ValuesBucket = { 'name': name }
const predicates = new relationalStore.RdbPredicates('user')
predicates.equalTo('id', id)
return store.update(valueBucket, predicates)
}
// 删除数据
async function deleteUser(store: relationalStore.RdbStore, id: number): Promise<number> {
const predicates = new relationalStore.RdbPredicates('user')
predicates.equalTo('id', id)
return store.delete(predicates)
}import distributedKVStore from '@ohos.data.distributedKVStore'
// 创建 KV-Store
const options: distributedKVStore.Options = {
createIfMissing: true,
encrypt: false,
backup: false,
autoSync: true, // 自动同步到其他设备
kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION
}
async function createKVStore(context: Context): Promise<distributedKVStore.SingleKVStore> {
return distributedKVStore.createKVStore(context, 'distributed_store', options)
}
// 写入
kvStore.put('sync_key', 'sync_value')
// 读取
const value = await kvStore.get('sync_key')
// 同步数据到其他设备
kvStore.sync(['device_id_1', 'device_id_2'], distributedKVStore.SyncMode.PUSH_ONLY)import fileIo from '@ohos.file.fs'
// 应用私有目录
const filesDir = context.filesDir // /data/app/el2/100/.../files
const cacheDir = context.cacheDir // /data/app/el2/100/.../cache
const tempDir = context.tempDir // /data/app/el2/100/.../temp
const preferencesDir = context.preferencesDir
// 写文件
const file = fileIo.openSync(`${filesDir}/data.json`, fileIo.OpenMode.CREATE | fileIo.OpenMode.WRITE_ONLY)
fileIo.writeSync(file.fd, JSON.stringify(data))
fileIo.closeSync(file)
// 读文件
const readFile = fileIo.openSync(`${filesDir}/data.json`, fileIo.OpenMode.READ_ONLY)
const content = fileIo.readSync(readFile.fd)
fileIo.closeSync(readFile)
// 判断文件是否存在
const exists = fileIo.accessSync(`${filesDir}/data.json`)