1. Remote Communication Kit概述

Remote Communication Kit(远场通信服务)是华为推出的 HTTP 数据请求封装工具,旨在帮助应用便捷、快速地向服务器发起数据请求,核心提供两大能力:

  • HTTP 请求能力:区别于 Network Kit 的标准 HTTP 能力,该套件构建了场景化 API,侧重易用性,适配各类 HTTP 网络请求场景,开发者可按需选择;
  • URPC 通信能力:即 Unified Remote Procedure Call(高性能 rpc 通信库),支持远程函数调用,具备抗弱网传输、多径传输(蜂窝网络 + Wi-Fi)等特性,简化远程过程调用开发。

    aaa.png

2. 基础准备:HarmonyOS6 网络权限配置

2.1 申请网络权限

在module.json5文件中配置网络相关权限,确保 HarmonyOS6 应用通信功能正常运行:

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      },
      {
        "name": "ohos.permission.GET_NETWORK_INFO"
      }
    ]
  }
}

3. HarmonyOS6 快速入门:HTTP 请求核心流程

3.1导入核心模块

import { rcp } from "@kit.RemoteCommunicationKit";
import { BusinessError } from '@kit.BasicServicesKit';

3.2 发起基础请求

以 POST 请求为例,展示 HarmonyOS6 下完整的请求创建、发起及结果处理流程:

//1.准备请求地址url
  const url = "http://10.0.2.2:3000/students";
  //2.创建请求对象rcp.Request
  const request = new rcp.Request(url, 'POST', {
    "content-type": 'application/json'
  },
    {
      "id": "5",
      "name": "张飞",
      "phoneNumber": "13100138000",
      "birthdate": "2025-01-03",
      "chineseScore": 20,
      "mathScore": 20,
      "englishScore": 20,
      "hobbies": "音乐, 编程",
      "createTime": "2025-01-03T12:00:00Z",
      "updateTime": "2025-01-03T14:00:00Z"
    }
  );
  //3.创建一个会话会想
  let session = rcp.createSession() 
  //4.发起请求处理结果
  session.fetch(request)
    .then((resp: rcp.Response) => {
      console.log("状态码:" + resp.statusCode)
      //处理请求成功的结果
      if (resp.statusCode >= 200 && resp.statusCode < 300) {
        console.log("请求成功:" + JSON.stringify(resp))
      } else {
        console.log("请求失败:" + JSON.stringify(resp))
      }
    })
    .catch((err: BusinessError) => {
      //处理请求失败的结果
      console.log("请求失败:" + JSON.stringify(err))
    })

4. HarmonyOS6 全场景 HTTP 请求示例

4.1 GET 请求(无参数)

//第一步:创建Session会话对象
let sessioin: rcp.Session = rcp.createSession()

//第二步:发起请求
let url = "http://10.0.2.2:3000/students"
sessioin.get(url)
  .then((data: rcp.Response) => {
    console.log("响应结果:" + data.toString())
  })
  .catch((err: BusinessError) => {
    console.log("错误消息:" + err.message)
  })
  .finally(() => {
    console.log("请求结束关闭会话")
    sessioin.close()
  })

4.2 GET 请求(带参数)

//URL地址
let urlObject = url.URL.parseURL("http://10.0.2.2:3000/students")
//URL参数,同时进行URL编码
let urlParams = new url.URLParams({
  id: "1",
  name: "田七"
})
//将参数拼接到URL地址上
urlObject.search = urlParams.toString()
console.log(urlObject.toString()) //http://10.0.2.2:3000/students?id=1&name=%E7%94%B0%E4%B8%83

let session = rcp.createSession()
session.get(urlObject)
  .then((data: rcp.Response) => {
    console.log("响应数据:" + data.toString())
  })
  .catch((error: Error) => {
    console.log("错误信息:" + JSON.stringify(error))
  })
  .finally(() => {
    session.close()
  })

4.3 POST 请求

//第一步:创建Session会话对象
const session = rcp.createSession();

//第二步:发起请求
let url = "http://10.0.2.2:3000/students"
session.post(url, {
  id: "2",
  name: "王五",
  phoneNumber: "13600136000",
  birthdate: "1999-03-03",
  chineseScore: 76,
  mathScore: 79,
  englishScore: 91,
  hobbies: "旅行, 摄影",
  createTime: "2023-10-01T12:00:00Z",
  updateTime: "2023-10-02T14:00:00Z"
})
  .then((data: rcp.Response) => {
    console.info(`响应结果: ${data.toString()}`);
  })
  .catch((err: BusinessError) => {
    console.error(`错误消息: 错误码是 ${err.code}, 消息是 ${JSON.stringify(err)}`);
  })
  .finally(() => {
    console.log("rcp请求结束")
    session.close()
  })

4.4 PUT 请求(更新数据)

//第一步:创建Session会话对象
const session = rcp.createSession();

//第二步:发起请求
let url = "http://10.0.2.2:3000/students/2"
session.put(url, {
  id:"2",
  name: "王d锤",
  phoneNumber: "13600136000",
  birthdate: "2000-03-03",
  chineseScore: 99,
  mathScore: 100,
  englishScore: 100,
  hobbies: "徒步, 骑行",
  createTime: "2020-10-01T12:00:00Z",
  updateTime: "2020-10-02T14:00:00Z"
})
  .then((data: rcp.Response) => {
    console.info(`响应结果: ${data.toString()}`);
  })
  .catch((err: BusinessError) => {
    console.error(`错误消息: 错误码是 ${err.code}, 消息是 ${JSON.stringify(err)}`);
  })
  .finally(() => {
    console.log("rcp请求结束")
    session.close()
  })

4.5 DELETE 请求(删除数据)

//第一步:创建Session会话对象
let session: rcp.Session = rcp.createSession()

//第二步:发起请求
let url = "http://10.0.2.2:3000/students/2"
session.delete(url)
  .then((data: rcp.Response) => {
    console.log("响应结果:" + data.toString())
  })
  .catch((err: BusinessError) => {
    console.log("错误消息:" + err.message)
  })
  .finally(() => {
    console.log("请求结束关闭会话")
    session.close()
  })

4.6 Fetch 通用请求(灵活配置)

适用于 HarmonyOS6 下需要自定义请求头、请求方法等复杂场景:

//第一步:创建会话对象
const session: rcp.Session = rcp.createSession()

//第二步:创建请求对象
let url = "http://10.0.2.2:3000/students/2"        //请求url
let httpMethod: rcp.HttpMethod = "PUT"                //请求方式
let headers: rcp.RequestHeaders = {'accept': 'application/json'}    //请求头
let modifiedContent: Student = {                            //请求体
  name: "zhangsan"
}
let request: rcp.Request = new rcp.Request(url, httpMethod, headers, modifiedContent)

//第三步:发起请求
session.fetch(request)
  .then((data: rcp.Response) => {
    console.log("响应数据:" + data.toString())
  })
  .catch((error: Error) => {
    console.log("错误消息:" + JSON.stringify(error))
  })
  .finally(() => {
    console.log("关闭会话")
    session.close()
  })

5. HarmonyOS6 文件下载实战

5.1 基础文件下载(带进度跟踪)

针对 HarmonyOS6 优化,支持配置超时时间、监听下载进度,适用于大文件下载场景:

//会话配置
const sessionConfiguration: rcp.SessionConfiguration = {
  //请求参数配置
  requestConfiguration: {
    //传输时间配置
    transfer:{
        timeout:{
          connectMs:  60000, //创建链接的时间(60s)
          transferMs: 60000*60,  //数据传输的时间(1个小时)
        }
    },
    //跟踪配置
    tracing: {
      httpEventsHandler: {
        onDownloadProgress: (totalSize: number, transferredSize: number) => {
          console.log("总进度:" + totalSize + ",当前进度:" + transferredSize)
        }
      }
    }
  }
}

const rcpSession = rcp.createSession(sessionConfiguration);
//定义文件路径
let filepath = getContext(this).filesDir + "/a.dmg"
return rcpSession.downloadToFile("https://harmonyos-api.oss-cn-beijing.aliyuncs.com/Apipost_mac_x64_8.1.10.dmg", {
  kind: "file",
  file: filepath  //文件路径
})
  .then(() => {
    console.log("下载成功")
    console.log("文件路径:"+filepath)
  })
  .catch(() => {
    console.log("下载失败")
  })
  .finally(() => {
    rcpSession.close();
  });
})

5.2 下载文件并保存到 HarmonyOS6 相册

适配 HarmonyOS6 系统相册机制,下载图片 / 视频后同步到系统相册:

const sessionConfiguration: rcp.SessionConfiguration = {
  requestConfiguration: {
    tracing: {
      httpEventsHandler: {
        onDownloadProgress: (totalSize: number, transferredSize: number) => {
          let progress = Number((transferredSize / totalSize * 100).toFixed(2))
          console.log("当前进度:" + progress + "%")
        }
      }
    }
  }
}

let filepath = this.context.filesDir + "a.jpg"

const rcpSession = rcp.createSession(sessionConfiguration);
rcpSession.downloadToFile("http://192.168.60.231:8081/itheima21.jpg", {
  kind: "file",
  file: filepath
})
  .then(async () => {
      await saveImageToAlbum(filepath);
      console.log("下载文件成功,文件保存到相册")
  })
  .finally(() => {
    rcpSession.close(); 
  });
async function saveImageToAlbum(sandboxPath: string) {
  //获取到一个图片访问助手
  const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(getContext());
  //根据沙箱路径获取文件的扩展名
  const fileNameExtension = sandboxPath.split('.').pop() || 'png';
  //图片创建的相关配置(扩展名, 图片/视频)
  const photoCreationConfig: photoAccessHelper.PhotoCreationConfig = {
    fileNameExtension,
    photoType: getPhotoType(fileNameExtension),
  };
  //获取沙箱路径的uri, 把/data/storage/el2/base/files/a.jpg转换为file://com.example.myapplication/data/storage/el2/base/files/a.jpg
  const uri: string = fileUri.getUriFromPath(sandboxPath);
  console.log("sandboxPath:" + sandboxPath)
  console.log("uri:" + uri)

  //打开保存图片或者视频的弹窗, 需要传递要保存文件的uri, 返回目标文件的uri数组
  const desFileUris: string[] = await phAccessHelper.showAssetsCreationDialog([uri], [photoCreationConfig]);
  const filePath = desFileUris[0];
  if (!filePath) {
    throw new Error('photo assets permission denied');
  }
  //将沙箱路径下的文件,复制到相册路径下
  copyFileSync(sandboxPath, filePath);
  //删除沙箱路径下的文件
  fs.unlinkSync(sandboxPath) //删除
  return filePath;
}

//根据扩展名获取图片类型(视频、图片)
function getPhotoType(fileNameExtension: string) {
  //常见的图片格式类型
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tiff', 'webp', 'svg'];
  //如果沙箱路径的扩展名是图片类型, 则返回photoAccessHelper.PhotoType.IMAGE(图片), 否砸返回photoAccessHelper.PhotoType.VIDEO(视频)
  return imageExtensions.includes(fileNameExtension) ?
  photoAccessHelper.PhotoType.IMAGE :
  photoAccessHelper.PhotoType.VIDEO;
}

//根据源文件路径和目标文件夹路径复制文件
function copyFileSync(srcPath: string, destPath: string) {
  const srcFile = fs.openSync(srcPath, fs.OpenMode.READ_ONLY);
  const destFile = fs.openSync(destPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  fs.copyFileSync(srcFile.fd, destFile.fd);
  fs.closeSync(srcFile);
  fs.closeSync(destFile);
}

6. HarmonyOS6 拦截器使用:统一请求处理

基于 HarmonyOS6 的拦截器机制,全局处理请求(如添加通用请求头、日志记录等):

6.1 定义拦截器(添加 Token)

class MyInterceptor implements rcp.Interceptor {
  intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
    //获取请求的url
    const url = context.request.url.href;
    console.log("拦截请求:" + url.toString())
    //在请求头中加入token
    if (context.request.headers) {
      context.request.headers.authorization =
        "jwttoken"
    }
    console.log("请求头:" + JSON.stringify(context.request.headers))
    return next.handle(context);
  }
} 

6.2 启用拦截器并发起请求

//会话配置参数
const sessionConfig: rcp.SessionConfiguration = {
  headers: {
    "content-type": "application/json",
  },
  interceptors: [new MyInterceptor()]
}

let session = rcp.createSession(sessionConfig)

session.get("http://10.0.2.2:3000/students/2")
  .then((data: rcp.Response) => {
    console.log("响应结果:" + data.toString())
  })
  .catch((error: Error) => {
    console.log("错误信息:" + JSON.stringify(error))
  })

7. 总结

HarmonyOS6 Remote Communication Kit 作为华为 HarmonyOS6 生态下的核心远场通信工具,围绕易用性、场景化、高性能三大核心设计,为 HarmonyOS6 应用开发提供全方位的 HTTP 通信能力支撑:

  1. 开发效率优化:针对 HarmonyOS6 特性提供 GET/POST/PUT/DELETE 等快捷 API,无需重复封装 HTTP 请求逻辑,同时支持 Fetch 通用请求满足自定义需求,大幅降低 HarmonyOS6 网络开发成本;
  2. 功能深度适配:内置适配 HarmonyOS6 的文件下载(含进度跟踪、超时配置)、系统相册同步、拦截器等能力,覆盖 HarmonyOS6 应用常规通信场景;
  3. 性能与稳定性:依托 URPC 能力,具备抗弱网、多径传输等特性,适配 HarmonyOS6 设备复杂网络环境;
  4. HarmonyOS6 最佳实践:所有请求需创建 Session 会话并在结束后关闭以释放 HarmonyOS6 系统资源;文件下载建议配置超时时间和进度跟踪提升用户体验;拦截器可统一处理 Token、日志等通用逻辑,降低 HarmonyOS6 代码冗余。
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐