元服务——5、接口解析
2024-11-30 11:30:04
22次阅读
0个评论
最后修改时间:2024-11-30 12:05:39
一、创建新项目
选择Application
点击finish
网络图片加载,Image('链接').属性
二、安装axios库
点击Terminal,
输入ohpm install @ohos/axios
回车, 导包import axios, { AxiosResponse } from '@ohos/axios';
如果报错,手动加载库
Build -> Clean Project
File -> Sync and Refresh Project
三、配置设置
对http的请求概述: 应用通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 HTTP数据请求功能主要由http模块提供。 使用该功能需要申请ohos.permission.INTERNET权限。 配置文件:
entry\src\main\module.json5
增加配置
,
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
四、model模型创建
创建model文件夹
model下建接口 示例返回数据
有几层就要创建几层model的ets文件,我们在其中看到address又是一个对象,所以得单独创建一个Address.ets的文件。
代码
import { Address } from "../model/Address";
export interface Users{
id:number;
name:string;
age:number;
email:string;
address:Address;
phone_number:string;
}
/*
* 用于承接返回数据
* */
export interface ApiResult<T> {
code:number;
msg:string;
date:T
}
import { Address } from "../model/Address";
export interface Users{
id:number;
name:string;
age:number;
email:string;
address:Address;
phone_numbers:string;
}
五、GET请求示例
pages文件夹下新建ShowUsers (ArkTS File文件),点检previewer预览
/*
* 引包操作
* */
import axios, { AxiosResponse } from '@ohos/axios';
import { Users } from '../model/Users';
import { BusinessError } from '@kit.BasicServicesKit';
import { JSON } from '@kit.ArkTS';
import { ApiResult } from '../model/ApiRest';
@Entry
@Component
struct GetDemo{
/*
* 返回数据
* */
@State info:Users[]|null=null;
/*
* 构建页面,单独存在的,里面无法放函数
* */
build() {
Column() {
Column() {
Text() {
Span("用 户 信 息")
}.fontSize(36)
.width('100%')
.margin({ top: '15%', left: '50%' })
}
Text().borderStyle(BorderStyle.Solid).borderWidth(1).width('100%')
List() {
ForEach(this.info, (u: Users, index) => {
ListItem() {
Column() {
Row() {
Text("编号:").fontSize(22)
Text(u.id.toString()).fontSize(22)
}.width('100%')
Row() {
Text("姓名:").fontSize(22)
Text(u.name.toString()).fontSize(22)
}.width('100%')
Row() {
Text("年龄:").fontSize(22)
Text(u.age.toString()).fontSize(22)
}.width('100%')
Row() {
Text("手机号:").fontSize(22)
Text(u.phone_numbers.toString()).fontSize(22)
}.width('100%')
Row() {
Text("邮箱:").fontSize(22)
Text(u.email.toString()).fontSize(22)
}.width('100%')
Row() {
Text("地址:").fontSize(22)
Text(){
Span(u.address.city.toString())
Span(u.address.country.toString())
Span(u.address.street.toString())
}.fontSize(22)
}.width('100%')
Text().borderStyle(BorderStyle.Solid).borderWidth(1).width('100%')
}.width('100%')
.justifyContent(FlexAlign.Start)
}
})
}
.listDirection(Axis.Vertical)
}
}
/*初始化的时候加载的函数*/
aboutToAppear(): void {
this.queryUsers();
}
/**
* GET请求函数
* 异步加载get请求
*/
async queryUsers() {
try {
const url = "http://39.107.126.100:5000/getInfo";
// 返回数据类型
const result: AxiosResponse<Users[]> =
await axios.get<ApiResult<Users[]>, AxiosResponse<Users[]>, null>(url);
this.info=result.data;
} catch (error) {
const err = error as BusinessError;
}
}
}
效果
六、POST请求示例
POST接口连接:https://openatom.atomgit.com/api/developer/recommend_list
模型层
ApiResult
export interface ApiResult<T> {
code: number;
msg: string;
data: T;
}
WareHouseList
export interface WareHouseList{
jump:string;
warehouseName:string;
}
Recommend
import { WareHouseList } from "./WareHouseList";
export interface Recommend{
nickname:string;
photo:string;
userId:string;
username:string;
profile:string;
jump:string;
isFocus:string;
focusButtonDisabled:string;
warehouseList:WareHouseList[];
}
Developer
import { Recommend } from "./Recommend"
export interface Developer{
records: Recommend[];
total:number;
size:number;
current:number;
pages:string;
}
引包操作
import axios, { AxiosResponse } from '@ohos/axios';
import { BusinessError } from '@kit.BasicServicesKit';
import { Developer } from '../model/Developer';
import { Recommend } from '../model/Recommend';
返回数据
@State info: Developer | null = null;
遍历展示数据
import axios, { AxiosResponse } from '@ohos/axios';
import { BusinessError } from '@kit.BasicServicesKit';
import { Developer } from '../model/Developer';
import { Recommend } from '../model/Recommend';
PersistentStorage.persistProp<string>("token", "");
@Entry
@Component
struct ShowIndex {
scroller: Scroller = new Scroller();
@State url: string = "https://openatom.atomgit.com/api/developer/recommend_list";
@State info: Developer | null = null;
build() {
Scroll(this.scroller) {
Column(){
ForEach(this.info?.records,(rec:Recommend,index)=>{
Column(){
Text(rec.nickname)
Image(rec.photo).width(50)
Text(rec.userId)
Text(rec.username)
Text(rec.jump)
}
})
}.width('100%')
}
}
aboutToAppear(): void {
this.getOrgList();
}
async getOrgList() {
interface RequestParam {
pageSize: number;
pageNum: number;
isSelected: number;
}
const param: RequestParam = {
pageSize: 10,
pageNum: 1,
isSelected: 0
};
axios.post(this.url, param, {
headers: {
"X-ATOMGIT-POP-COMMUNITY": "openatom"
}
}).then((ret: AxiosResponse) => {
this.info=ret.data["data"];
console.log(`请求结果:${JSON.stringify(ret.data["data"])}`);
}).catch((error: BusinessError) => {
console.error(`请求异常:${JSON.stringify(error)}`);
})
}
}
11