HarmonyOS鸿蒙Next中http请求的封装
HarmonyOS鸿蒙Next中http请求的封装
1 自定义请求消息头
2 支持GET和POST
3 将拿到的JSON数据 可以封装转化成对象或者LIST
4 回复
网络请求axios三方库可以支持自定义请求头和转换数据
更多关于HarmonyOS鸿蒙Next中http请求的封装的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS NEXT中,HTTP请求封装主要通过模块化的方式实现。系统提供了@ohos.net.http
模块处理网络请求,开发者需在module.json5中声明网络权限(ohos.permission.INTERNET)。核心步骤:1. 创建HttpRequest对象;2. 设置请求参数(URL、方法、头信息);3. 发起请求并处理回调。异步请求使用Promise/async语法,响应数据通过on(‘header’)和on(‘data’)事件获取。注意Next版本弃用了部分旧API,需使用http.createHttp()
替代原有创建方式。错误处理需监听on(‘error’)事件。
在HarmonyOS Next中封装HTTP请求可以这样做:
- 自定义请求头: 使用http.createHttp()创建请求对象后,通过setHeader()方法设置请求头:
let httpRequest = http.createHttp();
httpRequest.setHeader("Content-Type", "application/json");
httpRequest.setHeader("Authorization", "Bearer token");
- 支持GET/POST请求: 封装一个通用请求方法:
async function request(url: string, method: "GET"|"POST", data?: object) {
let httpRequest = http.createHttp();
let options = {
method: method,
header: { 'Content-Type': 'application/json' }
};
if (method === "POST" && data) {
options['extraData'] = JSON.stringify(data);
}
return httpRequest.request(url, options);
}
- JSON数据转换: 使用泛型进行类型安全的转换:
interface ResponseData<T> {
code: number;
data: T;
}
async function getData<T>(url: string): Promise<T> {
const response = await request(url, "GET");
const result: ResponseData<T> = JSON.parse(response.result);
return result.data;
}
// 使用示例
interface User {
id: number;
name: string;
}
const userList = await getData<User[]>("/api/users");
完整封装示例:
class HttpService {
private httpRequest = http.createHttp();
async request<T>(url: string, method: "GET"|"POST", data?: object): Promise<T> {
const options = {
method,
header: this.getHeaders()
};
if (method === "POST" && data) {
options['extraData'] = JSON.stringify(data);
}
const response = await this.httpRequest.request(url, options);
return JSON.parse(response.result).data;
}
private getHeaders() {
return {
'Content-Type': 'application/json',
'Authorization': 'Bearer token'
};
}
}
这种封装方式提供了类型安全的HTTP请求处理,同时支持自定义请求头和GET/POST方法。