在尝试HarmonyOS应用开发的时候需要用到网络请求调取接口数据,随手封装了一个可复用的ArkTS网络请求(半成品),不一定好,但是能用,这里来解释一下代码的部分,interface baseHeader用于给请求头封装时间戳,随机数,签名等用于与api接口交互验证身份,其余的代码如下:
import http from '@ohos.net.http';
import { ApiBaseUrl, ApiBaseUrl1 } from "./config";
import { data } from '../data/interface';
interface BaseHeader {
'TIMESTAMP': string;
'RANDOMSTR': string;
'SIGNATURE': string;
'CLIENT': string;
'Authorization'?: string;
};
// 定义请求头
const createHeaders = (): BaseHeader => {
const headers: BaseHeader = {
"TIMESTAMP": 'a',
"RANDOMSTR": 'b',
"SIGNATURE": 'c',
'CLIENT': 'd',
};
// 检查是否有用户登录后的token,有则在header中携带
const token = AppStorage.Get('token');
if (token) {
headers.Authorization = "jwt " + token;
}
return headers;
};
// 定义通用的API请求函数
export default async function api(
method: 'GET' | 'POST',
url: string,
data?: data,
useDefault: boolean = true
): Promise<data | null> {
let result: data | null = null;
const httpRequest: http.HttpRequest = http.createHttp();
const completeUrl: string = useDefault ? ApiBaseUrl + url : ApiBaseUrl1 + url;
// 封装options
const options: http.HttpRequestOptions = {
method: method === 'GET' ? http.RequestMethod.GET : http.RequestMethod.POST,
header: createHeaders(),
};
if (data) {
options.extraData = data;
}
try {
const response = await httpRequest.request(completeUrl, options);
if (response.responseCode === 200) {
result = typeof response.result === 'string' ? JSON.parse(response.result) : response.result;
} else {
// TODO: 对于更多状态码的处理
console.error(`Error: Received status code ${response.responseCode}`);
}
} catch (err) {
// 请求失败,进行失败逻辑处理
console.error('Request failed', err);
}
return result;
}
页面中调用方法如下,可以通过async/await来等待数据请求的完成,这里只是基于Hello World页面做的一个演示demo:
import api from '../common/api';
import apiUrl from '../common/api_url';
import { data } from '../data/interface'
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@State page: number = 1;
@State res: data = {};
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button('调用数据', { type: ButtonType.Capsule, stateEffect: true })
.onClick(async () => {
const data = {
use_last_asking: true,
page_size: 12,
page: this.page,
};
this.page += 1;
this.res = await api('GET', apiUrl.postList, data);
console.log('count:', this.res.count);
})
}.justifyContent(FlexAlign.Center)
.width('100%')
}
.height('100%')
}
}