写点什么

鸿蒙 NEXT 开发 - 网络管理

作者:东林知识库

1. 网络管理-应用权限

1.1 概述

应用权限保护的对象可以分为数据和功能:


  • 数据包含了个人数据(如照片、通讯录、日历、位置等)、设备数据(如设备标识、相机、麦克风等)、应用数据。

  • 功能则包括了设备功能(如打电话、发短信、联网等)、应用功能(如弹出悬浮框、创建快捷方式等)等。


根据授权方式的不同,权限类型可分为 system_grant(系统授权)和 user_grant(用户授权)。


应用在申请权限时,需要在项目的配置文件中,逐个声明需要的权限,否则应用将无法获取授权。

1.2 配置方式

  • 配置文件权限声明

  • 向用户申请授权

1.3 用法


编辑


在 module.json5 文件中加上(也就是在 module 下面加上 requestPermissions)


{  "module": {    "name": "entry",      "type": "entry",      "description": "$string:module_desc",      "mainElement": "EntryAbility",      "deviceTypes": [      "phone",      "tablet",      "2in1"    ],      "requestPermissions":[      {        "name" : "ohos.permission.INTERNET",        "reason": "$string:reason",        "usedScene": {          "abilities": [            "FormAbility"          ],          "when":"inuse"        }      }    ],
复制代码


参考文档


文档中心

2. 网络管理-HTTP 请求

2.1 概述

HTTP 数据请求功能主要由 http 模块提供。


使用该功能需要申请 ohos.permission.INTERNET 权限。

2.2 接口


编辑

2.3 开发步骤

  1. 从 @ohos.net.http 中导入 http 命名空间。

  2. 调用 createHttp()方法,创建一个 HttpRequest 对象。

  3. 调用该对象的 on()方法,订阅 http 响应头事件,此接口会比 request 请求先返回。可以根据业务需要订阅此消息。

  4. 调用该对象的 request()方法,传入 http 请求的 url 地址和可选参数,发起网络请求。

  5. 按照实际业务需要,解析返回结果。

  6. 调用该对象的 off()方法,取消订阅 http 响应头事件。

  7. 当该请求使用完毕时,调用 destroy()方法主动销毁。

2.4 简单代码示例

import http from '@ohos.net.http'
@Entry@Componentstruct Index { build() { Column() { Text('测试http请求').onClick(()=>{ // 创建http对象 const httpRequest = http.createHttp() // 发送请求 httpRequest.request('http://open.ibestservices.com/basic-api/platformCms/cms/door/index/info?siteId=1') .then(res => { console.log('http测试' + JSON.stringify(res.result)) }) }) }.width('100%') .height('100%') }}
复制代码


注意:console.log 输出数据的大小不能超过 1kb,要不然打印不出来

3. 网络管理-第三方库 axiso 使用

3.1 概述

axios 是一个基于 JavaScript 的开源库,用于在浏览器和 Node.js 等环境中发送 HTTP 请求。它支持 Promise API,并简化了 XMLHttpRequests 和 Fetch API 的使用,为开发者提供了一种简洁易用的方式来实现 AJAX 请求。

3.2 主要特性

  1. 跨平台支持:Axios 在浏览器端通过 XMLHttpRequests 发送请求,在 Node.js 中则使用 http/https 模块发送请求。

  2. Promise API:所有网络请求方法都返回 Promise 对象,使得异步编程更加简洁和易于处理。

  3. 拦截请求与响应:提供了全局和实例级别的请求和响应拦截器,可以在请求发送前或响应返回后进行预处理、错误处理或数据转换等操作。

  4. 取消请求:支持主动取消已发出但还未完成的 HTTP 请求。

  5. 自动转换 JSON 数据:Axios 自动将来自服务器的 JSON 数据转换为 JavaScript 对象,并自动序列化 POST、PUT 等请求体中的 JSON 数据为字符串发送。

  6. 配置灵活性:允许自定义请求头、URL 参数、超时时间等多种配置项,适用于不同场景下的 API 调用需求。

  7. 请求方法多样:支持所有标准的 HTTP 方法(GET、POST、PUT、DELETE 等),并对 PATCH 等非标准方法提供良好支持。

  8. 上传下载进度监控:支持监听文件上传和下载的进度事件

3.3 用法

@ohos/axios 是基于 axios 库进行适配的模块,使其可以运行在 鸿蒙 中。它沿用了 axios 库的现有用法和特性,为 HarmonyOS 项目的开发提供了便利。

3.3.1 安装 axios 依赖

打开编辑器里面终端,输入以下命令


ohpm install @ohos/axios
复制代码



编辑

3.3.2 申请网络权限

要请求网络数据,首先需要申请权限,需要在module.json5文件中设置网络访问权限


在 module.json5 文件中加上(也就是在 module 下面加上 requestPermissions)


{  "module": {    "name": "entry",      "type": "entry",      "description": "$string:module_desc",      "mainElement": "EntryAbility",      "deviceTypes": [      "phone",      "tablet",      "2in1"    ],      "requestPermissions":[      {        "name" : "ohos.permission.INTERNET",        "reason": "$string:reason",        "usedScene": {          "abilities": [            "FormAbility"          ],          "when":"inuse"        }      }    ],
复制代码

3.3.3 直接使用

import axios, { AxiosError, AxiosResponse } from '@ohos/axios';
@Entry @Component struct Index { build() { Column() { Text('测试axios') .onClick(() => { axios.get('http://open.ibestservices.com/basic-api/platformCms/cms/door/index/info?siteId=1') .then((res: AxiosResponse) => { console.log("get - 返回数据:" + JSON.stringify(res)); }) .catch((err: AxiosError) => { console.log("result:" + err.message); });
}) }.width('100%') .height('100%') } }
复制代码

3.3.4 封装使用

注意 baseURL: 'http://****:8099/' 里面的 ip 和端口要切换成对应自己的接口 ip 和端口


import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios'import router from '@ohos.router';import { promptAction } from '@kit.ArkUI';

/** * axios封装 */const httpRequest = axios.create({ baseURL: 'http://****:8099/', headers: { 'Content-Type': 'application/json', "Channel": "B2B" }, method: "post",})

/** * 添加请求拦截器 */httpRequest.interceptors.request.use((config: InternalAxiosRequestConfig) => { // 获取数据 const token: string | undefined = AppStorage.get("token") // 获取token if (token) { config.headers.Authorization = token } return config;}, (error: AxiosError) => { // 对请求错误做些什么 return Promise.reject(error);});

/** * 添加响应拦截器 */httpRequest.interceptors.response.use((response: AxiosResponse) => { console.log('响应数据' + JSON.stringify(response)) // 判断响应状态码 if (response.status === 200) { // 请求成功 if (response.data.code === 200) { return Promise.resolve(response.data.data); } else if (response.data.code === 401) { clearLoginInfoAndGoLoginPage(); } } promptAction.showToast({ message: response.data.message || '请求错误', duration: 2000, }) return Promise.reject(response);}, (error: AxiosError) => { promptAction.showToast({ message: '网络错误,换个网络试试', duration: 2000, }) return Promise.reject(error);});

/** * 清除用户信息并跳到登录页面 */async function clearLoginInfoAndGoLoginPage() { // 401错误 -> 清理用户信息,跳转到登录页 // 清理token,返回登录页 // 跳转首页路由 router.pushUrl({ url: 'pages/Login' })}
export default httpRequest;
复制代码


import httpRequest from '../request/Request'
/** * 用户接口 */class UserApi { /** * 获取验证码接口 */ getCode = (data: string) => { return httpRequest.get('/v1/user/getCode?phone=' + data) }}
const userApi = new UserApi();
export default userApi as UserApi;
复制代码


注意:手机号记得填写真实的


import UserApi from '../api/UserApi';
@Entry @Component struct Login { /** * 获取验证码 */ getCode() { UserApi.getCode('你的手机号'); }
build() { Column() { Text('获取验证码').onClick(() => { this.getCode() }) }.width('100%') .height('100%') } }
复制代码


发布于: 2 小时前阅读数: 9
用户头像

享受当下,享受生活,享受成长乐趣! 2025-02-26 加入

鸿蒙、Java、大数据

评论

发布
暂无评论
鸿蒙NEXT开发-网络管理_东林知识库_InfoQ写作社区