前言到读
消失了一段时间,这次也是参加社区的活动。所以准备重新写一些文章分享给大家, 今天分享是鸿蒙next 网络请求部分的, 之前分享了一个基于RCP 基础版本的,现在分享一个完整版本的,那么废话不多说我们正式开始
具体实现
这里我们主要讲究get 请求和post 请求 其他的还有put 请求和delete 请求用得相对较少有兴趣的同学可以查阅我们的官网的文档即可。
定义对外单例
typescript
export class OkRcpUtils {
public static instance: OkRcpUtils | null = null
// 设置方法为私有
private constructor() {
}
public static getInstance() {
if (!OkRcpUtils.instance) {
OkRcpUtils.instance = new OkRcpUtils()
}
return OkRcpUtils.instance
}
}
2 定义接手map 参数方法 这里我们使用建造者模式
typescript
/**
*
* @param map
* @returns
* 通过map方式提交参数
*/
public parmas(map?: Map<string, string> | undefined): OkRcpUtils {
this.parmasmap = map;
return this;
}
3 定义接收键值对参数方法 这里我们使用建造者模式
kotlin
/**
* 设置请求参数
* @param key
* @param val
* @returns
*/
public addparmas(key: string, val: string): OkRcpUtils {
if (this.parmasmap == null || this.parmasmap == undefined) {
this.parmasmap = new Map<string, string>();
}
this.parmasmap.set(key, val)
return this;
}
4 定义请求头扩展方法
kotlin
/**
*
*
* @param key
* @param val
* @returns
* 添加请求头
*
*
*/
public addheader(key: string, val: string): OkRcpUtils {
if (this.headersmap == null || this.headersmap == undefined) {
this.headersmap = new Map<string, string>();
}
this.headersmap.set(key, val)
return this;
}
5 定义get请求 方法
csharp
public rcpGet<T>(url: string): Promise<T|null> {
return this.rcpRequestparams(url, "GET");
}
6 定义 post 请求方法 (表单提交 )
ruby
public rcpPost<T>(url: string):Promise<T|null>{
return this.rcpRequestparams(url, "POST");
}
7 定义post提交 (json 格式)
csharp
public rcpPostjson<T>(url: string, paramsjson?: string): Promise<T|null>{
return this.rcpRequestjson(url, "POST", paramsjson);
}
8 组装请求数据
csharp
private rcpRequestparams<T>(url: string, method: string): Promise<T|null> {
let params: string = '';
let geturl: string = url;
if (method == "GET") {
if (this.parmasmap != undefined && this.parmasmap != null) {
geturl = geturl + "?" + Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap);
Logger.error("geturl" + geturl)
}
return this.baseRcpRequest(geturl, method)
} else {
if (this.parmasmap != undefined && this.parmasmap != null) {
params = Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap); // 表单提交
}
return this.baseRcpRequest(geturl, method, 'application/x-www-form-urlencoded', params)
}
}
9 组装请求扩展参数
typescript
let headers:rcp.RequestHeaders={
}
if(this.headersmap!=null&&this.headersmap!=undefined){
const jsonObj: Record<string, string> = {};
this.headersmap.forEach((value, key) => {
if (key && value) {
jsonObj[key] = value;
}
});
if(headerssting!=undefined){
jsonObj['content-type'] = headerssting;
}
headers=jsonObj;
}else {
if(headerssting!=undefined){
headers={
'content-type':headerssting
}
}
}
10 创建 session实例
ini
let session=rcp.createSession();
11 创建 Request 实例
csharp
let req=new rcp.Request(url,method,headers,params)
12 定义泛型返回
csharp
let getjson: T | null|string = null;
13 发起请求并获取服务器响应数据
javascript
return session.fetch(req).then((respone)=>{
Logger.error(`请求成功 success ${JSON.stringify(respone)}` );
if (respone.statusCode === 200) {
Logger.error("请求成功");
let result = `${JSON.stringify(respone)}`;
Logger.error("请求返回数据", result);
getjson = JSON.parse(result) as T;
Logger.error("请求返回数据", result);
} else {
getjson = null;
}
session.close()
return getjson;
}).catch((err:BusinessError)=>{
session.close();
Logger.error("err err code "+err.code+ "err message = "+err.message);
return null;
});
完整代码
kotlin
import { BusinessError, Request } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
import { HttpReqInterceptor } from './HttpReqInterceptor';
import Logger from './Logger';
import { Md5Utils } from './Md5Utils';
/***
*
* 创建人:xuqing
* 创建时间:2025年6月4日15:17:15
* 类说明:网络请求工具类
*
*
*/
export class OkRcpUtils {
public static instance: OkRcpUtils | null = null
private parmasmap: Map<string, string> | undefined;
private headersmap: Map<string, string> | undefined;
// 设置方法为私有
private constructor() {
}
public static getInstance() {
if (!OkRcpUtils.instance) {
OkRcpUtils.instance = new OkRcpUtils()
}
return OkRcpUtils.instance
}
/**
*
* @param map
* @returns
* 通过map方式提交参数
*/
public parmas(map?: Map<string, string> | undefined): OkRcpUtils {
this.parmasmap = map;
return this;
}
/**
* 设置请求参数
* @param key
* @param val
* @returns
*/
public addparmas(key: string, val: string): OkRcpUtils {
if (this.parmasmap == null || this.parmasmap == undefined) {
this.parmasmap = new Map<string, string>();
}
this.parmasmap.set(key, val)
return this;
}
/**
*
*
* @param key
* @param val
* @returns
* 添加请求头
*
*
*/
public addheader(key: string, val: string): OkRcpUtils {
if (this.headersmap == null || this.headersmap == undefined) {
this.headersmap = new Map<string, string>();
}
this.headersmap.set(key, val)
return this;
}
public rcpGet<T>(url: string): Promise<T|null> {
return this.rcpRequestparams(url, "GET");
}
public rcpPost<T>(url: string):Promise<T|null>{
return this.rcpRequestparams(url, "POST");
}
public rcpPostjson<T>(url: string, paramsjson?: string): Promise<T|null>{
return this.rcpRequestjson(url, "POST", paramsjson);
}
private rcpRequestparams<T>(url: string, method: string): Promise<T|null> {
let params: string = '';
let geturl: string = url;
if (method == "GET") {
if (this.parmasmap != undefined && this.parmasmap != null) {
geturl = geturl + "?" + Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap);
Logger.error("geturl" + geturl)
}
return this.baseRcpRequest(geturl, method)
} else {
if (this.parmasmap != undefined && this.parmasmap != null) {
params = Md5Utils.getInstance().getPostBodyFormParamMap(this.parmasmap); // 表单提交
}
return this.baseRcpRequest(geturl, method, 'application/x-www-form-urlencoded', params)
}
}
private rcpRequestjson<T>(url: string, method: string, params?: string): Promise<T|null>{
return this.baseRcpRequest(url, method, 'application/json', params)
}
private baseRcpRequest<T>(url: string, method: string, headerssting?: string,
params?: string): Promise<T|null> {
let headers:rcp.RequestHeaders={
}
if(this.headersmap!=null&&this.headersmap!=undefined){
const jsonObj: Record<string, string> = {};
this.headersmap.forEach((value, key) => {
if (key && value) {
jsonObj[key] = value;
}
});
if(headerssting!=undefined){
jsonObj['content-type'] = headerssting;
}
headers=jsonObj;
}else {
if(headerssting!=undefined){
headers={
'content-type':headerssting
}
}
}
let session=rcp.createSession();
let req=new rcp.Request(url,method,headers,params)
let getjson: T | null|string = null;
return session.fetch(req).then((respone)=>{
Logger.error(`请求成功 success ${JSON.stringify(respone)}` );
if (respone.statusCode === 200) {
Logger.error("请求成功");
let result = `${JSON.stringify(respone)}`;
Logger.error("请求返回数据", result);
getjson = JSON.parse(result) as T;
Logger.error("请求返回数据", result);
} else {
getjson = null;
}
session.close()
return getjson;
}).catch((err:BusinessError)=>{
session.close();
Logger.error("err err code "+err.code+ "err message = "+err.message);
return null;
});
}
}
具体调用
1 链式调用通过addparmas 添加请求参数
vbnet
let respost=await OkRcpUtils.getInstance()
.addparmas("username", "18674049006")
.addparmas("password", "123456").rcpGet<LoginModel>(this.LOGIN);
if(respost?.code==200){
Logger.error("respost"+respost.msg)
Logger.error("respost"+respost.code)
Logger.error("respost"+respost.user)
}

2 通过map 的方式添加请求参数
kotlin
OkRcpUtils.getInstance().parmas(map).rcpGet<LoginModel>(this.LOGIN).then((data)=>{
Logger.error("data-- >" + data?.code);
Logger.error("data-- >" + data?.code);
Logger.error("data-- >" + data?.msg);
})

3 post请求 表单提交
go
const map: Map<string, string> = new Map<string, string>();
map.set("username", "18674049006");
map.set("password", "123456");
OkRcpUtils.getInstance().parmas(map).rcpPost<LoginModel>(this.LOGIN).then((data)=>{
Logger.error("OkRcpUtils data --- > "+data?.msg)
Logger.error("OkRcpUtils data --- > "+data?.code)
Logger.error("OkRcpUtils data --- > "+data?.msg)
})

4 post json提交

我们通过日志截图里面的数据我们无论是用post或者get 都可以顺利请求到我们服务器的数据,并且我们定义了返回类型是泛型 我们在拿到服务器返回的数据的时候我们就直接解析调数据将json 解析格式化成为我们的model (class 或者 interface都可以 ) 我们在view层只需要直接获取我们的model里面属性即可
最后总结:
鸿蒙next 里面rcp 网络请求相对比较简单,但是这里只是简单提到了用法 ,例如还有拦截器还没有设置,这些希望同学们可以自己去完善 老师这边只是提供一个基本的思路,今天的文章就讲到这里有兴趣的同学可以拿老师代码去优化修改, 今天的文章就讲到这里有兴趣的 关注我B站教程 了解更多鸿蒙开发的知识 可以关注坚果派公众号 。 谢谢
课程地址
www.bilibili.com/cheese/play...
项目内容:
1 常用布局组件的学习
2 网络请求工具类封装
3 arkui 生命周期启动流程
4 日志工具类的封装
5 自定义组合组件的封装
6 路由导航跳转的使用
7 本地地数据的缓存 以及缓存工具类的封装
8 欢迎页面的实现
9 登录案例和自动登录效果实现
10 请求网络数据分页上拉加载 下拉刷新的实现
11 list数据懒加载实现
12 webview组件的使用
如果使用更多好用的鸿蒙next三方库
友情链接
harmony-utils 一款功能丰富且极易上手的HarmonyOS工具库,借助众多实用工具类,致力于助力开发者迅速构建鸿蒙应用,能够满足各种不同的开发需求。
harmony-dialog 一款极为简单易用的零侵入弹窗,仅需一行代码即可轻松实现,无论在何处都能够轻松弹出。