的博客园.|

菜鸟de博客

园龄:1年10个月粉丝:2关注:1

2024-03-19 21:14阅读: 58评论: 0推荐: 0

3.19 HarmonyOS 网络请求工具类

网络请求部分的代码实在是太麻烦了,所以把他封装成一个工具类使用起来方便些

今天先封装两个,一个是post把集合传给后端,一个是get查询全部

复制代码
import http from '@ohos.net.http';

class AxiosUtil {
private httpRequest = http.createHttp();

constructor() {
// 用于订阅HTTP响应头
this.httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
}

public async getAllUtil(url: string): Promise<any> {
return new Promise((resolve, reject) => {
this.httpRequest.request(
url,
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
},
usingCache: true,
priority: 1,
connectTimeout: 60000,
readTimeout: 60000,
usingProtocol: http.HttpProtocol.HTTP1_1,
},
(err, data) => {
if (!err) {
try {
const res = JSON.parse(data.result as string);
resolve(res); // 解析成功后 resolve 出去
} catch (parseError) {
reject(parseError); // JSON 解析失败时 reject 出去
}
} else {
console.info('error:' + JSON.stringify(err));
this.httpRequest.off('headersReceive');
this.httpRequest.destroy();
reject(err); // 发生错误时 reject 出去
}
},
);
});
}

public async postUtil(postclass: object, url: string): Promise<any> {
const requestBody = JSON.stringify(postclass);

return new Promise((resolve, reject) => {
this.httpRequest.request(
url,
{
method: http.RequestMethod.POST,
header: {
'Content-Type': 'application/json'
},
extraData: requestBody,
expectDataType: http.HttpDataType.STRING,
usingCache: true,
priority: 1,
connectTimeout: 60000,
readTimeout: 60000,
usingProtocol: http.HttpProtocol.HTTP1_1,
},
(err, data) => {
if (!err) {
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(data.responseCode));
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + JSON.stringify(data.cookies));
resolve(
data.result
);
} else {
console.info('error:' + JSON.stringify(err));
this.httpRequest.off('headersReceive');
this.httpRequest.destroy();
reject(err);
}
},
);
});
}
}

export default AxiosUtil;

复制代码

然后就可以在别的界面直接调用咯


import AxiosUtil from '../common/util/axiosUtil';
class CourseDetails {
coursename: string;
teacher: string;
classroom: string;

constructor(coursename: string, teacher: string, classroom: string) {
this.coursename = coursename;
this.teacher = teacher;
this.classroom = classroom;
}
}

@Entry
@Component
struct AxiosPage {
courseDetails: CourseDetails = new CourseDetails('jack5', '王建', '206');
@State Return:string = 'error'
@State students:Object[] = null
axiosInstance:AxiosUtil = new AxiosUtil();
url : string = 'http://localhost:8080/newcourse'
url2 : string = 'http://localhost:8080/book'

async get() {
// 在适当的地方调用 postUtil 方法
this.Return = await this.axiosInstance.postUtil(this.courseDetails,this.url);
}

async get2() {
this.students = await this.axiosInstance.getAllUtil(this.url2)
// 在适当的地方调用 postUtil 方法
}
build() {
Row() {
Column() {
List(){
ForEach(this.students,item=>{
ListItem(){
Row(){
Text(item.bookName)
}
}
})
}
Text(this.Return)
Button('发送')
.onClick(() => this.get())
Button('发送2')
.onClick(() => this.get2())
}
.width('100%')
}
.height('100%')
}
}

本文作者:菜鸟de博客

本文链接:https://www.cnblogs.com/zeyangshuaige/p/18083975

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   菜鸟de博客  阅读(58)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起