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

昭通建设网站厦门公司注册程序注册程序

昭通建设网站,厦门公司注册程序注册程序,深圳空间设计有限公司,牧风的在wordpress文章目录 基本使用封装参考 基本使用 鸿蒙应用发起HTTP请求的基本使用,如下: 导入http模块创建httpRequest对象发起http请求,并处理响应结果 第一、导入http模块: import http from ohos.net.http第二、创建httpRequest对象&a…

文章目录

    • 基本使用
    • 封装
    • 参考

基本使用

鸿蒙应用发起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
http://www.sczhlp.com/news/128513/

相关文章:

  • 网站开发首选语言外国做家具的网站
  • 烟台手机网站建设费用百度人气榜排名
  • 企业网站建设的目的论文亚马逊雨林有多恐怖
  • 网站用什么开发软件做网站开发个人简历word下载
  • 网站改版做301dedecms网站建设合同
  • 网站界面用什么做wordpress 4.0
  • 高端人才做兼职的招聘网站有哪些腐女做喜欢的网站
  • Gitee:本土化代码托管平台如何重塑中国开发者协作生态
  • WEB项目引入druid监控配置
  • Computer Graphics Tutorial
  • CF1874(CF Round 901) 总结
  • 专业类网站零基础网站开发要学多久
  • php mysql开发的网站免费开商城网站
  • 做家具的企业网站巴中市城乡和住房建设局网站
  • 山西省建设厅网站太湖县城乡建设局网站
  • 2. Spring AI 快速入门使用 - Rainbow
  • PyCharm 2025.1安装包下载与安装教程
  • 阿里将发布多模态模型 Qwen3-Omni,主打多语言与复杂推理;DeepvBrowser 上线 AI 语音浏览器丨日报
  • Word文档内容批量替换脚本 - wanghongwei
  • 企业网站推广方案设计毕业设计网站除了wordpress外
  • 知名网站建设公如何给企业做网络推广
  • 网页设计的特点有哪些东莞seoseo优化排名
  • 上海网站建设开发哪家好德州市建设工程质量监督站网站
  • 北京商城网站开发公司河北保定最新通知
  • 哪一个网站做专栏作家好点seo培训网的优点是
  • 注册完域名怎么做网站网站网站开发人员犯法吗
  • VMware ESXi 磁盘置备类型详解
  • EF 数据迁移生成sql脚本
  • HWiNFO 硬件信息检测工具下载与安装教程
  • 第七章 手写数字识别V1