![cover](https://img-blog.csdnimg.cn/img_convert/60b04f0c92ee49ecb12bfea536f61927.png)
HarmonyOS鸿蒙ArkTS/ArkUI项目,封装http网络请求,封装公共API以及调用请求的过程实现。
我们在日常当中开发鸿蒙项目的时候,调用@ohos.net.http (数据请求)方法去请求接口,整个组件的语法糖会很繁琐,我们对@ohos.net.http (数据请求)方法进行一下二次公共API接口封装http网络请求,实现接口的简单方便快捷的调用。
·
我们在日常当中开发鸿蒙项目的时候,调用@ohos.net.http (数据请求)方法去请求接口,整个组件的语法糖会很繁琐,我们对@ohos.net.http (数据请求)方法进行一下二次公共API接口封装http网络请求,实现接口的简单方便快捷的调用。
一、封装api.ets,将常用的post、get、put、delete请求进行封装。
// api.ets文件
const BASE_URL: string = 'http://120.46.58.55';//这里写接口地址
import http from '@ohos.net.http';
export function httpRequestDel(url: string) {
url = BASE_URL+url
let httpRequest = http.createHttp();
var header = {
'Content-Type': 'application/json',
}
let responseResult = httpRequest.request(url, {
method: http.RequestMethod.DELETE,
header: header
});
return responseResult
}
export function httpRequestPut(url: string, params: any) {
url = BASE_URL+url
let httpRequest = http.createHttp();
var header = {
'Content-Type': 'application/json',
}
let responseResult = httpRequest.request(url, {
method: http.RequestMethod.PUT,
extraData: params,
header: header
});
return responseResult
}
export function httpRequestPost(url: string, params: any) {
url = BASE_URL+url
let httpRequest = http.createHttp();
var header = {
'Accept': '*/*',
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
};
let responseResult=httpRequest.request(url, {
method: http.RequestMethod.POST,
extraData: params,
header: header
});
return responseResult
}
export function httpRequestGet(url: string,query: any) {
url = BASE_URL+url+query
let httpRequest = http.createHttp();
var header = {
'Content-Type': 'application/json',
}
let responseResult = httpRequest.request(url, {
method: http.RequestMethod.GET,
header: header
});
return responseResult
}
二、请求调用封装的公共接口api.ets
// @ts-nocheck
import {httpRequestPost} from './api/api';
import Url from '@ohos.url'
@Entry
@Component
struct Login {
@State username:string='';
@State password:string='';
build() {
Column() {
// header();
TextInput({ placeholder: '请输入账号',text:this.username }).margin({ top: 20 })
.onChange((value:string)=>{
this.username=value;
})
TextInput({ placeholder: '请输入密码',text:this.password }).type(InputType.Password).margin({ top: 20 })
.onChange((value:string)=>{
this.password=value;
})
Button('登录')
.width(200)
.margin({ top: 20 })
.backgroundColor('#ff832317')
.onClick(()=>{
//参数处理
let body: Map<string, any> = new Map<string, any>();
body.set("username", this.username)
body.set("password", this.password)
let param = new Url.URLParams(Object.fromEntries(body)).toString();
//新封装方法测试
let responseResult=httpRequestPost('/api/login3',param)
responseResult.then((res)=>{
if (res.responseCode=200) {
let data:JSON=JSON.parse(res.result);
console.info(res.responseCode);
console.info(data);
};
}).catch((err)=>{
console.log(err);
});
})
}.padding(20)
}
}
export default Login
本文原创,原创不易,如需转载,请联系作者授权。
更多推荐
所有评论(0)