当前位置: 首页 > news >正文

HarmonyOS鸿蒙应用开发——HTTP网络访问与封装

文章目录

    • 基本使用
    • 封装
    • 参考

基本使用

鸿蒙应用发起HTTP请求的基本使用,如下:

  • 导入http模块
  • 创建httpRequest对象
  • 发起http请求,并处理响应结果

第一、导入http模块:

import http from '@ohos.net.http'

第二、创建httpRequest对象,注意的是每一个httpRequest对象对应一个http请求任务,不可复用。

 const httpRequest = http.createHttp()

第三、发起请求,比如POST请求

 httpRequest.request(// 请求url地址url,{// 请求方式method: http.RequestMethod.POST,// 请求的额外数据。extraData: {"param1": "value1","param2": "value2",},// 可选,默认为60sconnectTimeout: 60000,// 可选,默认为60sreadTimeout: 60000,// 开发者根据自身业务需要添加header字段header: {'Content-Type': 'application/json'}}).then((data) => { if (data.responseCode === http.ResponseCode.OK) {// 处理响应结果// data.result为服务器返回的业务数据console.info('Result:' + data.result);console.info('code:' + data.responseCode);}
}).catch((err) => {console.info('error:' + JSON.stringify(err));
});

最后需要声明网络权限,在module.josn5文件中声明:

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

上面就是网络请求的简单使用,接下来通过Promise来封装一个网络请求库,统一管理请求参数、响应数据、日志的输出等,对外屏蔽了细节,使用者只需定义业务数据的实体类以及调用即可。

封装

以**玩Android**开放接口为测试用例

定义业务数据的实体类,通过泛型来接收不同的数据类型:

export class ResponseResult<T> {errorCode: number;errorMsg: string;data?: T | Object | string;
}

把各种请求方式用枚举声明RequestMethod

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

其实在http模块中已经有对应的枚举,之所以再用一个新枚举来声明,是简化使用,同时也是将http模块相关细节屏蔽掉不对外开放,这样可以灵活替换网络库。

定义一个HttpUtils类实现:

const  TAG = "HttpUtils"
const BASE_URL = "https://www.wanandroid.com"
export class HttpUtils{public static readonly SUCCESS_CODE: number = 0public static readonly READ_TIME_OUT = 60 * 1000public static readonly CONNECT_TIME_OUT = 60 * 1000private baseUrl: string = ""constructor(baseUrl: string) {this.baseUrl = baseUrl}private methodName(method: RequestMethod): http.RequestMethod {switch (method){case RequestMethod.OPTIONS:{return http.RequestMethod.OPTIONS}case RequestMethod.GET:{return http.RequestMethod.GET}case RequestMethod.HEAD:{return http.RequestMethod.HEAD}case RequestMethod.POST:{return http.RequestMethod.POST}case RequestMethod.PUT:{return http.RequestMethod.PUT}case RequestMethod.DELETE:{return http.RequestMethod.DELETE}case RequestMethod.TRACE:{return http.RequestMethod.TRACE}case RequestMethod.CONNECT:{return http.RequestMethod.CONNECT}}}request<T>(path: string, reqMethod: RequestMethod, parameter: Map<string, Object> = null): Promise<T | null> {// 注意的是每一个httpRequest对象对应一个http请求任务,不可复用。const httpRequest = http.createHttp()const method = this.methodName(reqMethod)let extraData = {}let url = `${this.baseUrl}/${path}`if (parameter != null) {switch (reqMethod) {case RequestMethod.POST: {extraData = Object.fromEntries(parameter)break;}case RequestMethod.GET: {const urlParams = Object.keys(parameter).map(key => `${key}=${parameter[key]}`).join('&')if (url.includes("?")) {url = `${url}${urlParams}`} else {url = `${url}?${urlParams}`}break;}}}LogUtils.debug(TAG, "==================Request====================")LogUtils.debug(TAG, "url: " + url)LogUtils.debug(TAG, "method: " + method.toString())if (reqMethod == RequestMethod.POST)LogUtils.debug(TAG, "extraData: " + JSON.stringify(parameter, null, 2))return new Promise((resolve, reject) => {httpRequest.request(url,{method,readTimeout: HttpUtils.READ_TIME_OUT,connectTimeout: HttpUtils.CONNECT_TIME_OUT,header: {'Content-Type': 'application/json'},extraData}).then((value) => {LogUtils.debug(TAG, "==================Response====================")LogUtils.debug(TAG, "url: " + url)LogUtils.debug(TAG, "method: " + method.toString())LogUtils.debug(TAG, "header: " + JSON.stringify(value.header, null, 2))LogUtils.debug(TAG, "responseCode: " + value.responseCode)LogUtils.debug(TAG, "resultType: " + value.resultType)if (value.responseCode == http.ResponseCode.OK) {let result: ResponseResult<T> = JSON.parse(value.result.toString())LogUtils.debug(TAG, "body: " + JSON.stringify(result, null, 2))if (result.errorCode == HttpUtils.SUCCESS_CODE) {resolve(result.data as T)} else {reject(result.errorMsg)}} else {reject("请求失败")}}).catch((reason) => {reject(reason)})})}get<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {return this.request<T>(path, RequestMethod.GET, parameter)}post<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {return this.request<T>(path, RequestMethod.POST, parameter)}delete<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {return this.request<T>(path, RequestMethod.DELETE, parameter)}put<T>(path: string, parameter: Map<string, Object> = null): Promise<T | null> {return this.request<T>(path, RequestMethod.PUT, parameter)}}
const YiNet = new HttpUtils(BASE_URL)
export default YiNet

使用发起网络请求:

  aboutToAppear() {let map = new Map<string,string>()map["cid"] = 294YiNet.get<ArticleList>("project/list/1/json",map).then((data)=>{this.data = JSON.stringify(data, null, 2)})let map2 = new Map<string,string>()map2["username"] = "123"map2["password"] = "123456"YiNet.post<User>("user/login",map2).then((data)=>{this.data = JSON.stringify(data, null, 2)}).catch((err)=>{Prompt.showToast({message:err})})}

日志输出:

在这里插入图片描述

参考

  • https://developer.huawei.com/consumer/cn/training/course/slightMooc/C101667364948559963?ha_linker=eyJ0cyI6MTcwMjE3NzI3OTYyMywiaWQiOiI4MmM3ZTI1MmFmMDJlMDZiODBmOGU1ZDM5ZTI5YmMyOCJ9
  • https://www.wanandroid.com/blog/show/2

相关文章:

  • C/C++语言的安全编码规范
  • ssh安装和Gitee(码云)源码拉取
  • 设计模式篇---代理模式
  • Kafka 最佳实践:构建可靠、高性能的分布式消息系统
  • 基于JAVA+SpringBoot+Vue的前后端分离的医院信息智能化HIS系统
  • linux下查看文件当下的所有文件的大小和查找大文件
  • 【Spring Boot 源码学习】ApplicationListener 详解
  • JWT的原理
  • pyqt5使用Designer实现按钮上传图片
  • Vue 纯css方式实现自定义进度条组件
  • SQL注入概述
  • ffmpeg6.0之ffprobe.c源码分析二-核心功能源码分析
  • git 常用的使用方法
  • 初识Redis
  • 「Verilog学习笔记」多bit MUX同步器
  • 【笔记】你不知道的JS读书笔记——Promise
  • CNN 在图像分割中的简史:从 R-CNN 到 Mask R-CNN
  • CSS实用技巧干货
  • docker python 配置
  • extjs4学习之配置
  • iOS 系统授权开发
  • JavaScript HTML DOM
  • JavaScript服务器推送技术之 WebSocket
  • JDK9: 集成 Jshell 和 Maven 项目.
  • MySQL主从复制读写分离及奇怪的问题
  • 阿里云应用高可用服务公测发布
  • 初识MongoDB分片
  • 第2章 网络文档
  • 七牛云 DV OV EV SSL 证书上线,限时折扣低至 6.75 折!
  • 微信开源mars源码分析1—上层samples分析
  • 微信小程序开发问题汇总
  • 一文看透浏览器架构
  • 硬币翻转问题,区间操作
  • 用 Swift 编写面向协议的视图
  • Redis4.x新特性 -- 萌萌的MEMORY DOCTOR
  • 交换综合实验一
  • ​创新驱动,边缘计算领袖:亚马逊云科技海外服务器服务再进化
  • # 再次尝试 连接失败_无线WiFi无法连接到网络怎么办【解决方法】
  • #100天计划# 2013年9月29日
  • #define用法
  • $nextTick的使用场景介绍
  • (10)Linux冯诺依曼结构操作系统的再次理解
  • (不用互三)AI绘画工具应该如何选择
  • (带教程)商业版SEO关键词按天计费系统:关键词排名优化、代理服务、手机自适应及搭建教程
  • (二十三)Flask之高频面试点
  • (十六)、把镜像推送到私有化 Docker 仓库
  • (图)IntelliTrace Tools 跟踪云端程序
  • (转)Oracle存储过程编写经验和优化措施
  • .NET CLR基本术语
  • .net on S60 ---- Net60 1.1发布 支持VS2008以及新的特性
  • .net 调用php,php 调用.net com组件 --
  • .NET 漏洞分析 | 某ERP系统存在SQL注入
  • .NET 某和OA办公系统全局绕过漏洞分析
  • .NET/C# 使用反射调用含 ref 或 out 参数的方法
  • .net安装_还在用第三方安装.NET?Win10自带.NET3.5安装