【鸿蒙应用ArkTS开发系列】- http网络库使用讲解和封装

news/2024/7/21 9:30:17 标签: harmonyos, http, 华为, ArkTS
http://www.w3.org/2000/svg" style="display: none;">

目录

  • 前言
  • http网络库组件介绍
  • http网络库封装
    • 创建Har Module
    • 创建RequestOption 配置类
    • 创建HttpCore核心类
    • 创建HttpManager核心类
    • 对外组件导出
    • 添加网络权限
  • http网络库依赖和使用

前言

现在网上的应用,基本都是网络应用,需要进行联网获取数据,而常用的联网获取数据的方式有http、socket、websocket等。

在鸿蒙应用、服务中,stage模式开发下,鸿蒙官方为我们提供了一个网络组件库 http ,我们通过

import http from ‘@ohos.net.http’; 即可以完成引用。

http_10">http网络库组件介绍

@ohos.net.http (数据请求)
该组件提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。
具体查看官网
通过官网的介绍,可以很快上手该组件的使用,下面我们对该网络库进行简单的封装,方便我们的使用

http_16">http网络库封装

网络库工程结构如下图:
https://img-blog.csdnimg.cn/ba56421b7c32447fad356062b627ae24.png" alt="在这里插入图片描述" />
具体步骤如下:

  1. 创建Har Module
  2. 创建RequestOption请求配置类
  3. 创建HttpCore核心类
  4. 创建HttpManager对外管理类
  5. 对外组件导出
  6. 添加网络权限

创建Har Module

我们创建一个Module ,类型选择为Har,3.1Beta IDE选择 Visual Library,这里我们创建module名称为

httpLibrary。

创建RequestOption 配置类

代码如下:

/**
 * <pre>
 * @desc  : 网络请求配置
 * </pre>
 */
export interface RequestOptions {

  /**
   * Request url.
   */
  url?: string;

  /**
   * Request method.
   */
  method?: RequestMethod; // default is GET

  /**
   * Request url queryParams  .
   */
  queryParams ?: Record<string, string>;

  /**
   * Additional data of the request.
   * extraData can be a string or an Object (API 6) or an ArrayBuffer(API 8).
   */
  extraData?: string | Object | ArrayBuffer;

  /**
   * HTTP request header.
   */
  header?: Object; // default is 'content-type': 'application/json'

}

export enum RequestMethod {
  OPTIONS = "OPTIONS",
  GET = "GET",
  HEAD = "HEAD",
  POST = "POST",
  PUT = "PUT",
  DELETE = "DELETE",
  TRACE = "TRACE",
  CONNECT = "CONNECT"
}

这里字段大家可自行拓展,我这里简单添加了几个常用字段,包括url、urlParams、header、extraData、大家也可以增加一些诸如UserAgent之类的网络配置。

创建HttpCore核心类

该类使我们这个网络库的主要核心代码实现,主要封装’@ohos.net.http的API调用,提供便捷使用的API。

import http from '@ohos.net.http';
import { RequestOptions } from './RequestOptions';

/**
 * Http请求器
 */
export class HttpCore {

  /**
   * 发送请求
   * @param requestOption
   * @returns Promise
   */
  request<T>(requestOption: RequestOptions): Promise<T> {
    return new Promise<T>((resolve, reject) => {
      this.sendRequest(requestOption)
        .then((response) => {
          if (typeof response.result !== 'string') {
            reject(new Error('Invalid data type'));

          } else {
            let bean: T = JSON.parse(response.result);
            if (bean) {
              resolve(bean);
            } else {
              reject(new Error('Invalid data type,JSON to T failed'));
            }

          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  }


  private sendRequest(requestOption: RequestOptions): Promise<http.HttpResponse> {

    // 每一个httpRequest对应一个HTTP请求任务,不可复用
    let httpRequest = http.createHttp();

    let resolveFunction, rejectFunction;
    const resultPromise = new Promise<http.HttpResponse>((resolve, reject) => {
      resolveFunction = resolve;
      rejectFunction = reject;
    });

    if (!this.isValidUrl(requestOption.url)) {
      return Promise.reject(new Error('url格式不合法.'));
    }

    let promise = httpRequest.request(this.appendQueryParams(requestOption.url, requestOption.queryParams), {
      method: requestOption.method,
      header: requestOption.header,
      extraData: requestOption.extraData, // 当使用POST请求时此字段用于传递内容
      expectDataType: http.HttpDataType.STRING // 可选,指定返回数据的类型
    });

    promise.then((response) => {

      console.info('Result:' + response.result);
      console.info('code:' + response.responseCode);
      console.info('header:' + JSON.stringify(response.header));


      if (http.ResponseCode.OK !== response.responseCode) {
        throw new Error('http responseCode !=200');
      }
      resolveFunction(response);

    }).catch((err) => {
      rejectFunction(err);
    }).finally(() => {
      // 当该请求使用完毕时,调用destroy方法主动销毁。
      httpRequest.destroy();
    })
    return resultPromise;
  }


  private appendQueryParams(url: string, queryParams: Record<string, string>): string {

    // todo 使用将参数拼接到url上
    return url;
  }

  private isValidUrl(url: string): boolean {

    //todo 实现URL格式判断
    return true;

  }
}

export const httpCore = new HttpCore();

代码讲解:

  1. expectDataType: http.HttpDataType.STRING,这里固定了返回数据为string,大家也可以通过RequestOptions中定义字段传入,这里定义为string只是方便后续的string转Bean;
  2. 定义sendRequest方法。
  3. 对请求配置进行处理,这里进行对Url进行格式判断,如果非正确格式,需要对外抛出错误;需要进行Url参数拼接;可对请求参数、请求结果进行日志打印;对Http响应码进行判断,按200和非200请求码进行分类返回。
  4. 定义 request 进行请求结果转Bean的处理(这里默认返回数据为JSON 字符串,其他类型自行拓展),该方法也是对外的唯一函数。

创建HttpManager核心类

import { RequestOptions } from './RequestOptions';
import { httpCore as HttpCore } from './HttpCore';
/**
 * <pre>
 * @desc       : 对外管理器
 * </pre>
 */
export class HttpManager {
  private static mInstance: HttpManager;

  // 防止实例化
  private constructor() {
  }

  static getInstance(): HttpManager {
    if (!HttpManager.mInstance) {
      HttpManager.mInstance = new HttpManager();
    }
    return HttpManager.mInstance;
  }

  request<T>(option: RequestOptions): Promise<T> {
    return HttpCore.request(option);
  }
}

HttpManager 为对外API调用入口类,提供单例对象跟发送请求API。

对外组件导出

httpLibrary模块的根目录下有一个 index.ets文件,在该文件中进行需要对外导出的组件定义


export { HttpManager } from './src/main/ets/http/HttpManager';
export { RequestMethod } from './src/main/ets/http/RequestOptions';

到这里我们就完成了一个简易的网络库封装,我们可以将该module导出Har包对外提供,也可以直接在项目中使用该module。

添加网络权限

漏了一点,这里记得为该网络库添加上网络权限哦,在module.json5文件中

 "requestPermissions": [
      {
        "name": 'ohos.permission.INTERNET'
      }
    ]

http_256">http网络库依赖和使用

httphttpLibrary_258">依赖http网络库(httpLibrary)

打开entry下的 oh-package.json5文件,增加如下依赖:

"dependencies": {
    '@ohos/http_library': 'file:../httpLibrary'
  }

httphttpLibrary_267">使用http网络库(httpLibrary)

这里我们写一个例子,使用该网络库进行发送一个get请求

https://img-blog.csdnimg.cn/0d1fa22ecedc46ef94da7404ecfd8a2a.png" alt="在这里插入图片描述" />
在entry下,任意页面中,进行请求调用。

handleClick() {
    HttpManager.getInstance()
      .request<TestBean>({
        method: RequestMethod.GET,
        url: 'https://jsonplaceholder.typicode.com/todos/1' //公开的API
      })
      .then((result) => {
        console.info(JSON.stringify(result));
      })
      .catch((err) => {
        console.error(JSON.stringify(err));
      });
  }

https://jsonplaceholder.typicode.com/todos/1 是一个公开的get请求API(如果侵权,请联系我删除,谢谢!)
这里我们定一个了一个TestBean,进行数据解析

/**
 * <pre>
 * @desc       : 测试Bean
 * </pre>
 */
export interface TestBean {

  /**
   * {
   "userId": 1,
   "id": 1,
   "title": "delectus aut autem",
   "completed": false
   }
   */

  userId: number,
  id: number,
  title: string,
  completed: boolean

}

这样就完成了调用,接着我们将应用装机,点击获取数据按钮,可以在log面板看到如下输出:

https://img-blog.csdnimg.cn/b427810fbd38403e96004965fb98355a.png" alt="在这里插入图片描述" />
文章到此结束,需要Demo的或者是有问题交流的,欢迎评论区留言。


http://www.niftyadmin.cn/n/314829.html

相关文章

2022年美国大学生数学建模竞赛A题自行车运动员的能量特征解题全过程文档及程序

2022年美国大学生数学建模竞赛 A题 自行车运动员的能量特征 原题再现&#xff1a; 背景   自行车公路赛有多种类型&#xff0c;包括标准赛、团体计时赛和个人计时赛。这些比赛的自行车运动员获胜的机会可能会有所不同&#xff0c;具体取决于赛事的类型、路线和自行车运动员…

Microsoft Dynamics 365 Business Central 生产订单扣料的几种方法

学习目标&#xff1a; 掌握生产订单扣料的几种方法 学习内容&#xff1a; Forward flush by routing operation&#xff08;通过工序&#xff1a;向前扣料&#xff09;Backward flush by routing operation&#xff08;通过工序&#xff1a;向后扣料&#xff09;Forward flus…

有效和无效的帮助中心区别在哪?如何设计有效的帮助中心?

帮助中心就是一个丰富的知识库&#xff0c;可以对企业的潜在客户进行引导。不仅能够提升用户的使用体验还能为企业塑造更加专业的品牌形象&#xff0c;在使用过程中为用户提供帮助。帮助中心的目的就是为了解决用户在使用过程中遇到的困难&#xff0c;同时为用户的使用提供引导…

国产仪器 3986A/3986D/3986E/3986F/3986H噪声系数分析仪

3986系列噪声系数分析仪产品包括3986A(10MHz&#xff5e;4GHz)、3986D(10MHz&#xff5e;18GHz)、3986E(10MHz&#xff5e;26.5GHz)、3986F(10MHz&#xff5e;40GHz)和3986H(10MHz&#xff5e;50GHz)&#xff0c;具有频率覆盖范围宽、频段选择灵活、接收灵敏度高、用户界面友好…

玩客云直刷armbian自带宝塔7.5

文章目录 前言一、短接玩客云1.1、流程1.2、短接操作 二、获取固件底包2.1、下载固件2.2、刷入成功后获取ip地址2.3、登陆2.4、其他 总结 前言 一开始25买了一个玩客云&#xff08;主机电源&#xff09;玩玩&#xff0c;成功刷入armbian&#xff0c;但是就是安装不了宝塔&…

域名备案批量查询工具-域名备案查询

为什么域名要备案 域名备案是一种互联网服务管理制度。其主要目的是加强互联网信息管理&#xff0c;维护网络安全和公共利益&#xff0c;规范网站的使用和运营行为。备案对于网站和域名的合法性和正常运营都具有重要的意义。没有备案的域名无法在大陆境内访问&#xff0c;并可…

pytorch移植华为mindspore记录

因为某个需求&#xff0c;需要把原来pytorch的神经网络移植到华为的mindspore上 这边记录下遇到的坑 附上mindspore的官方教程&#xff1a; https://mindspore.cn/tutorials/zh-CN/r2.0/advanced/compute_graph.html 这边附上需要移植的网络&#xff0c;以tensorflow和pytorch…

可视化图表API格式要求有哪些?Sugar BI详细代码示例(4)

Sugar BI中的每个图表可以对应一个数据 API&#xff0c;用户浏览报表时&#xff0c;选定一定的过滤条件&#xff0c;点击「查询」按钮将会通过 API 拉取相应的数据&#xff1b;前面说过&#xff0c;为了确保用户数据的安全性&#xff0c;Sugar BI上的所有数据请求都在Sugar BI的…