【OpenHarmony 北向应用开发】Arkts服务卡片数据每秒刷新的实现?-鸿蒙开发者社区-51CTO.COM
在OpenHarmony上使用网络组件axios与Spring Boot进行前后端交互
仓库地址: axiosTest · AtomGit_开放原子开源基金会代码托管平台
结果演示:在OpenHarmony上使用网络组件axios与Spring Boot进行前后端交互_哔哩哔哩_bilibili

一,简单的交互
前端请求函数
1 2 3 4 5 6 7 8 9 10 11
| firstGet(): Promise<AxiosResponse>{ return axios.get('http://192.168.211.1:8090/test/1'); } getAaddB(a: number, b: number): Promise<AxiosResponse>{ return axios.get('http://192.168.211.1:8090/test/2', { params: { a: a,ts b: b } }) }
|
这两个函数是使用axios库发起HTTP GET请求的函数,用于与服务器进行通信
服务器端点: http://192.168.211.1:8090/test/1
这是我本机的ip地址和springboot运行端口,使用在windows终端输入ipconfig可查看
返回值: 该函数返回一个Promise,该Promise在请求成功时将包含AxiosResponse对象,其中包含了从服务器接收到的响应信息。
后端controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package com.example.demospring.controller; import org.springframework.web.bind.annotation.*; @RequestMapping("/test") @RestController public class test1 { @GetMapping("/1") public String test11(){ return "这是axios发送get请求从后端获取的数据"; } @GetMapping("/2") public int AB(@RequestParam int a, @RequestParam int b){ return a + b; } }
|
test1()
方法:
- 功能: 当接收到GET请求
/test/1
时,该方法返回一个字符串 “这是axios发送get请求从后端获取的数据”。
- 备注: 这是一个简单的用于演示GET请求的方法,返回字符串数据。
二,axios与Spring Boot进行前后端交互的实现
一,前后端交互配置
Arkts目录结构

前端axios封装一个简单的网络请求
在src/main/ets/network/AxiosRequest.ets里
1 2 3 4 5 6 7 8
| import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios'
axios.defaults.baseURL = "http://192.168.211.1:8090"
export default axios; export {AxiosResponse}
|
后端用于配置跨域资源共享(CORS)的设置
1 2 3 4 5 6 7 8 9
| @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("PUT", "GET", "POST", "DELETE") .allowedHeaders("*") .allowCredentials(false) .maxAge(300); }
|
@RequestMapping("/hello")
:这个注解用于类级别,表示所有在这个控制器中的方法的URL映射的基本路径
1 2 3 4 5
| @RestController @RequestMapping("/hello") public class SumUpController { ... }
|
二,不同请求的参数传递与后端接收返回代码
1.get请求获取数据
axios请求
1 2 3
| export function get1(): Promise<AxiosResponse> { return axios.get('/hello/get1'); }
|
后端controller
1 2 3 4
| @GetMapping("/get1") public String get1(){ return "这是你拿到的数据"; }
|
2.get请求传递多个参数
axios请求
1 2 3 4 5 6 7 8 9
| export function get2(a: number, b: number): Promise<AxiosResponse> { return axios.get('/hello/get2', { params: { a: a, b: b } }); }
|
后端controller
1 2 3 4 5
| @GetMapping("/get2")
public String get2(@RequestParam int a, @RequestParam int b){ return "你传的两个数是" + a + " " + b; }
|
@RequestParam 注解允许你自定义请求参数的名称,并提供其他选项,如设置默认值或将参数标记为必需
3.get请求路径参数
axios请求
1 2 3 4
| export function get3(ps: number, pn: number): Promise<AxiosResponse> { return axios.get(`/hello/get3/${pn}/${ps}`); }
|
后端controller
1 2 3 4
| @GetMapping("/get3/{pn}/{ps}") public String get3(@PathVariable("ps") int ps, @PathVariable("pn") int pn){ return "你的查找要求是一页" + ps + "条数据的第" + pn + "页"; }
|
@PathVariable("id")
表示要从路径中提取一个名为 “id” 的变量,并将其值绑定到 itemId
参数上。
4.get请求返回JSON数据
axios请求
1 2 3 4 5 6 7 8
| export interface ResponseData { status: string; message: string; } export function get4(): Promise<AxiosResponse<ResponseData>> { return axios.get('/hello/get4'); }
|
Promise<AxiosResponse<ResponseData>>
表示一个 Promise 对象,该对象最终解决为 Axios 发起的 HTTP 请求的响应,而该响应的数据体应该符合 ResponseData
类型的结构。
后端controller
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Data public static class ResponseData { private String status; private String message; } @GetMapping("/get4") public ResponseData get4() { ResponseData responseData = new ResponseData(); responseData.setStatus("success"); responseData.setMessage("这是一条成功的消息。"); return responseData; }
|
5.post 使用对象作为请求参数
axios请求
1 2 3
| export function post1(person: { name: string, age: number }): Promise<AxiosResponse> { return axios.post(`/hello/post1`, person); }
|
后端controller
1 2 3 4 5 6 7 8 9
| @Data public static class Person { private String name; private int age; } @PostMapping("/post1") public String post1(@RequestBody Person person) { return "你传的姓名: " + person.getName() + " 年龄: " + person.getAge() + "。"; }
|
6.post 使用Map接收JSON数据
axios请求
1 2 3 4
| export function post2(data: any): Promise<AxiosResponse> { return axios.post(`/hello/post2`, data); }
|
后端controller
1 2 3 4 5 6 7 8 9 10
| @PostMapping("/post2") public String post2(@RequestBody Map<String, String> mp) { AtomicReference<String> data = new AtomicReference<>(""); mp.forEach((k, v) ->{ data.set(data + k); data.set(data + ": "); data.set(data + v + ","); }); return "你传的键值对是: " + data; }
|
7.put请求
axios请求
1 2 3
| export function putExample(data: string): Promise<AxiosResponse> { return axios.put('/hello/putExample', {data: data}); }
|
后端controller
1 2 3 4
| @PutMapping("/putExample") public String putExample(@RequestBody String data) { return "这是PUT请求,传入的数据是: " + data; }
|
8.delete请求
axios请求
1 2 3
| export function deleteExample(id: number): Promise<AxiosResponse> { return axios.delete(`/hello/deleteExample/${id}`); }
|
后端controller
1 2 3 4
| @DeleteMapping("/deleteExample/{id}") public String deleteExample(@PathVariable("id") int id) { return "这是DELETE请求,要删除的数据ID是: " + id; }
|
三,调用传参
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import router from '@ohos.router' import {get1, get2, get3, get4, post1, post2, putExample, deleteExample} from '../network/api/TestApi' @Entry @Component struct Index { @State get1: string = ""; @State get2: number = undefined; @State get3: number = undefined; @State get4: {status: string, message: string} = null; @State post1: string = ""; @State post2: string = ""; @State put: string = ""; @State delete: string = ""; build() { Column() { Button("get1-get请求获取数据") .onClick(async () =>{ this.get1 = (await get1()).data; }) Text(this.get1) .fontSize(20) Button("get2-传递多个参数") .onClick(async () =>{ this.get2 = (await get2(1, 3)).data; }) Text(`${this.get2!=undefined?this.get2:""}`) .fontSize(20) Button("get3-路径参数") .onClick(async () =>{ this.get3 = (await get3(3, 4)).data; }) Text(`${this.get3!=undefined?this.get3:""}`) .fontSize(20) Button("get4-返回JSON数据") .onClick(async () =>{ this.get4 = (await get4()).data; }) Text(this.get4!=null ? JSON.stringify(this.get4) : "") .fontSize(20)
Button("post1-使用对象作为请求参数") .onClick(async () =>{ this.post1 = (await post1({name: "张三", age: 18})).data; }) Text(this.post1) .fontSize(20)
Button("post2-使用Map接收JSON数据的POST请求示例") .onClick(async () =>{ this.post2 = (await post2({id: "1", name: "李四", status: "call"})).data; }) Text(this.post2) .fontSize(20)
Button("put请求") .onClick(async () =>{ this.put = (await putExample("put data")).data; }) Text(this.put) .fontSize(20)
Button("delete请求") .onClick(async () =>{ this.delete = (await deleteExample(10)).data; }) Text(this.delete) .fontSize(20) Button("对一个表单的增删改查") .margin(20) .onClick(() =>{ router.pushUrl({ url: "pages/TalentTableTest" }) }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } }
|
四,总结
一、请求参数错误的常见情况:
- 参数名称不一致
- 参数类型(格式)不一致
- 缺少必须的请求参数
- 请求头信息不符合要求
二、不同请求方式与参数传递方式的对应关系:
- RESTful风格的API通常使用路径变量传递参数。在Spring框架中,可以使用
@PathVariable
注解来接收这些参数。
- URL中使用params传递参数时,通常使用
@RequestParam
注解来接收参数。
- 当客户端通过请求体传递JSON数据时,可以使用
@RequestBody
注解来接收。
@ModelAttribute
用于绑定方法参数或方法返回值到模型中,通常用于将请求参数与模型属性进行绑定。
三,参考:
网络组件axios可以在OpenHarmony上使用了-鸿蒙开发者社区-51CTO.COM
基于 axios 封装一个简单的网络请求-鸿蒙开发者社区-51CTO.COM
OpenHarmony三方库中心仓 axios
HTTP 条件请求 - HTTP | MDN (mozilla.org)
五,补充:
一、什么是请求体
请求体(RequestBody)是在HTTP协议中用于传输客户端向服务器发送的数据的部分。它是HTTP请求中可选的组成部分,用于向服务器传递请求所需的参数、内容或者数据。请求体通常出现在POST、PUT等请求方法中,用于发送客户端的数据给服务器。请求体可以包含各种类型的数据,如表单数据、JSON数据、文件等。具体的数据类型由请求头中的Content-Type字段来指定。常见的请求体格式有以下几种:
- 表单数据(application/x-www-form-urlencoded):以key-value形式编码
- JSON数据(application/json):用于传递结构化数据
- 文件上传(multipart/form-data):传递文件二进制数据和元数据
二、HTTP方法的常见使用场景:
GET:获取服务器资源
POST:向服务器提交数据
PUT:上传或更新资源
DELETE:删除服务器上的资源
PATCH:部分更新资源
OPTIONS:获取通信选项,用于跨域请求预检
HEAD:获取资源的元信息,不返回实体主体