HarmonyOS鸿蒙ArkTS,封装http网络请求
前提:
要想使用http请求,系统必须要具备ohos.permission.INTERNET权限,在model.json5文件中的module模块下添加如下请求权限:
在module.json5文件中
配置
"requestPermissions": [{"name": "ohos.permission.INTERNET"}
]
定义响应格式 Response:
在文件中定义,文件目录自定义
export default class Response {/*** 响应码*/code:number/*** 响应消息*/message:string/*** 响应数据*/data:any }
请求封装
//导入请求
import http from '@ohos.net.http';
//响应格式
import Response from '../inittype/public'//导出去一个请求函数 使用axios风格请求数据、参数可自行增加
export function request(url:string,method: http.RequestMethod,data?:any): Promise<Response> {const BASE_URL = "请求根地址"let httpRequest = http.createHttp();let responseResult = httpRequest.request( BASE_URL+ url,{method: method,//请求头设置header: {'Content-Type': 'application/json'},//携带额外参数extraData: JSON.stringify(data),});let response = new Response();// 处理数据,并返回return responseResult.then((result: http.HttpResponse) => {if (value.responseCode === 200) {let res: Response = JSON.parse(`${result.result}`);response.data = res.data;response.code = res.code;response.message = res.message;} else {response.message = '请求错误';response.code = 400;}return response;}).catch(() => {response.message = '请求错误';response.code = 400;return response;});
}
api封装
import http from '@ohos.net.http';
//导入封装好的请求
import { request } from '../utils/request'/*** 获取信息*/export default function getInfo(data) {return request(`/learun/adms/user/LoginByOaperson`,http.RequestMethod.POST,data)
}
使用:
至此整个请求封装结束