鸿蒙 ark ui 网络请求 我不允许你不会

2023-11-25 21:30

本文主要是介绍鸿蒙 ark ui 网络请求 我不允许你不会,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前言:

最近有在学习这个鸿蒙的ark ui开发 因为鸿蒙不是发布了一个鸿蒙next的测试版本 明年会启动纯血鸿蒙应用 所以我就想提前给大家写一些博客文章

效果图

11-24 16:26:22.005 25156-25156/com.example.httpsrequest E A0ff00/HTTPS: 请求状态 --> 200, %{public}s
11-24 16:26:22.006 25156-25156/com.example.httpsrequest E A0ff00/HTTPS: 请求成功, %{public}s
11-24 16:26:22.006 25156-25156/com.example.httpsrequest E A0ff00/HTTPS: 请求返回数据, "{\"ret\":1,\"data\":[{\"id\":\"8289\",\"title\":\"\\u6cb9\\u7116\\u5927\\u867e\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/9\\/8289.jpg\",\"collect_num\":\"1670\",\"food_str\":\"\\u5927\\u867e \\u8471 \\u751f\\u59dc \\u690d\\u7269\\u6cb9 \\u6599\\u9152\",\"num\":1670},{\"id\":\"2127\",\"title\":\"\\u56db\\u5ddd\\u56de\\u9505\\u8089\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/3\\/2127.jpg\",\"collect_num\":\"1592\",\"food_str\":\"\\u732a\\u8089 \\u9752\\u849c \\u9752\\u6912 \\u7ea2\\u6912 \\u59dc\\u7247\",\"num\":1592},{\"id\":\"30630\",\"title\":\"\\u8d85\\u7b80\\u5355\\u8292\\u679c\\u5e03\\u4e01\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/31\\/30630.jpg\",\"collect_num\":\"1552\",\"food_str\":\"QQ\\u7cd6 \\u725b\\u5976 \\u8292\\u679c\",\"num\":1552},{\"id\":\"9073\",\"title\":\"\\u5bb6\\u5e38\\u7ea2\\u70e7\\u9c7c\",\"pic\":\"http:\\/\\/www.qubaobei.com\\/ios\\/cf\\/uploadfile\\/132\\/10\\/9073.jpg\",\"co

具体实现:

添加网络访问权限 :

在module.json5 里面添加网络访问权限

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

创建HTTPS请求

HTTPS协议是位于应用层的一种安全传输协议,与HTTP最大的区别是服务端与客户端之间进行数据传输都会经过TLS/SSL加密。该示例请求测试接口地址,并将请求得到的再日志里面打印出来。效果如图所示:

请求工具类

首先在OkHttpUtil.ets中调用createHttp方法创建一个请求任务,再通过request方法发起网络请求。该方法支持三个参数:url、options以及callback回调,其中options可以设置请求方法、请求头以及超时时间等。

import http from '@ohos.net.http';
import Constants, { ContentType } from '../constant/Constants';
import Logger from './Logger';
import { NewsData } from '../viewmodel/NewsData';export function httpRequestGet(url: string) {return httpRequest(url, http.RequestMethod.GET);
}export function httpRequestPost(url: string, params?: NewsData) {return httpRequest(url, http.RequestMethod.POST, params);
}function httpRequest(url: string, method: http.RequestMethod,params?: NewsData){let httpRequest = http.createHttp();let responseResult = httpRequest.request(url, {method: method,readTimeout: Constants.HTTP_READ_TIMEOUT,//读取超时时间 可选,默认为60000msheader: {'Content-Type': ContentType.JSON},connectTimeout: Constants.HTTP_READ_TIMEOUT,//连接超时时间  可选,默认为60000msextraData: params // 请求参数});return responseResult.then((value: http.HttpResponse)=>{Logger.error("请求状态 --> "+value.responseCode)if(value.responseCode===200){Logger.error("请求成功");let getresult = value.result;Logger.error('请求返回数据', JSON.stringify(getresult));return getresult;}}).catch((err)=>{return "";});
}

日志工具类

/** Copyright (c) 2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import hilog from '@ohos.hilog';class Logger {private domain: number;private prefix: string;private format: string = '%{public}s, %{public}s';/*** constructor.** @param Prefix Identifies the log tag.* @param domain Domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF.*/constructor(prefix: string = 'MyApp', domain: number = 0xFF00) {this.prefix = prefix;this.domain = domain;}debug(...args: string[]): void {hilog.debug(this.domain, this.prefix, this.format, args);}info(...args: string[]): void {hilog.info(this.domain, this.prefix, this.format, args);}warn(...args: string[]): void {hilog.warn(this.domain, this.prefix, this.format, args);}error(...args: string[]): void {hilog.error(this.domain, this.prefix, this.format, args);}
}export default new Logger('HTTPS', 0xFF00)

然后在view中展示去点击触发请求

import webView from '@ohos.web.webview';
import http from '@ohos.net.http';
import httpGet from '../common/utils/HttpUtil';
import StyleConstant from '../common/constant/StyleConstant';
import CommonConstant from '../common/constant/CommonConstants';
import { httpRequestGet }  from '../common/utils/OKhttpUtil';@Entry
@Component
struct WebPage {controller: webView.WebviewController = new webView.WebviewController();@State buttonName: Resource = $r('app.string.request_button_name');@State webVisibility: Visibility = Visibility.Hidden;@State webSrc: string = CommonConstant.DISH;build() {Column() {Row() {Image($r('app.media.ic_network_global')).height($r('app.float.image_height')).width($r('app.float.image_width'))TextInput({ placeholder: $r('app.string.input_address'), text: this.webSrc }).height($r('app.float.text_input_height')).layoutWeight(1).backgroundColor(Color.White).onChange((value: string) => {this.webSrc = value;})}.margin({top: $r('app.float.default_margin'),left: $r('app.float.default_margin'),right: $r('app.float.default_margin')}).height($r('app.float.default_row_height')).backgroundColor(Color.White).borderRadius($r('app.float.border_radius')).padding({left: $r('app.float.default_padding'),right: $r('app.float.default_padding')})Row() {Web({ src: this.webSrc, controller: this.controller }).zoomAccess(true).height(StyleConstant.FULL_HEIGHT).width(StyleConstant.FULL_WIDTH)}.visibility(this.webVisibility).height(StyleConstant.WEB_HEIGHT).width(StyleConstant.FULL_WIDTH).align(Alignment.Top)Row() {Button(this.buttonName).fontSize($r('app.float.button_font_size')).width(StyleConstant.BUTTON_WIDTH).height($r('app.float.button_height')).fontWeight(FontWeight.Bold).onClick(() => {this.onRequest();})}.height($r('app.float.default_row_height'))}.width(StyleConstant.FULL_WIDTH).height(StyleConstant.FULL_HEIGHT).backgroundImage($r('app.media.ic_background_image', ImageRepeat.NoRepeat)).backgroundImageSize(ImageSize.Cover)}async onRequest() {httpRequestGet(CommonConstant.DISH).then((data)=>{console.log("data --- > "+data);});}
}

分析 模块源码 可知,通过request方法建立请求后,模块底层首先会调用三方库 libcurl 中的curl_easy_init初始化一个简单会话。初始化完成后,接着调用curl_easy_setopt方法设置传输选项。其中CURLOPT_URL用于设置请求的URL地址,对应request中的url参数;CURLOPT_WRITEFUNCTION可以设置一个回调,保存接收的数据;CURLOPT_HEADERDATA支持设置回调,在回调中保存响应头数据。

传输选项设置成功后,调用curl_multi_perform执行传输请求,并通过curl_multi_info_read查询处理句柄是否有消息返回,最后进入HandleCurlData方法处理返回数据。

最后总结

ark ui里面网络请求也比较简单 基本用法我上面的代码有展示了写法基本和前端的js很像 有兴趣的有同学可以深入去研究官网里面提到TLS和SSL 握手过程 我这里就不展开分析了

为了能让大家更好的学习鸿蒙 (Harmony OS) 开发技术,这边特意整理了《鸿蒙 (Harmony OS)开发学习手册》(共计890页),希望对大家有所帮助:https://qr21.cn/FV7h05

《鸿蒙 (Harmony OS)开发学习手册》

入门必看:https://qr21.cn/FV7h05

  1. 应用开发导读(ArkTS)
  2. 应用开发导读(Java)

HarmonyOS 概念:https://qr21.cn/FV7h05

  1. 系统定义
  2. 技术架构
  3. 技术特性
  4. 系统安全

如何快速入门:https://qr21.cn/FV7h05

  1. 基本概念
  2. 构建第一个ArkTS应用
  3. 构建第一个JS应用
  4. ……

开发基础知识:https://qr21.cn/FV7h05

  1. 应用基础知识
  2. 配置文件
  3. 应用数据管理
  4. 应用安全管理
  5. 应用隐私保护
  6. 三方应用调用管控机制
  7. 资源分类与访问
  8. 学习ArkTS语言
  9. ……

基于ArkTS 开发:https://qr21.cn/FV7h05

  1. Ability开发
  2. UI开发
  3. 公共事件与通知
  4. 窗口管理
  5. 媒体
  6. 安全
  7. 网络与链接
  8. 电话服务
  9. 数据管理
  10. 后台任务(Background Task)管理
  11. 设备管理
  12. 设备使用信息统计
  13. DFX
  14. 国际化开发
  15. 折叠屏系列
  16. ……

这篇关于鸿蒙 ark ui 网络请求 我不允许你不会的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/424641

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

豆包 MarsCode 不允许你还没有女朋友

在这个喧嚣的世界里,爱意需要被温柔地唤醒。为心爱的她制作每日一句小工具,就像是一场永不落幕的浪漫仪式,每天都在她的心田播撒爱的种子,让她的每一天都充满甜蜜与期待。 背景 在这个瞬息万变的时代,我们都在寻找那些能让我们慢下来,感受生活美好的瞬间。为了让这份浪漫持久而深刻,我们决定为女朋友定制一个每日一句小工具。这个工具会在她意想不到的时刻,为她呈现一句充满爱意的话语,让她的每一天都充满惊喜和感动

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

Linux 网络编程 --- 应用层

一、自定义协议和序列化反序列化 代码: 序列化反序列化实现网络版本计算器 二、HTTP协议 1、谈两个简单的预备知识 https://www.baidu.com/ --- 域名 --- 域名解析 --- IP地址 http的端口号为80端口,https的端口号为443 url为统一资源定位符。CSDNhttps://mp.csdn.net/mp_blog/creation/editor

ASIO网络调试助手之一:简介

多年前,写过几篇《Boost.Asio C++网络编程》的学习文章,一直没机会实践。最近项目中用到了Asio,于是抽空写了个网络调试助手。 开发环境: Win10 Qt5.12.6 + Asio(standalone) + spdlog 支持协议: UDP + TCP Client + TCP Server 独立的Asio(http://www.think-async.com)只包含了头文件,不依

poj 3181 网络流,建图。

题意: 农夫约翰为他的牛准备了F种食物和D种饮料。 每头牛都有各自喜欢的食物和饮料,而每种食物和饮料都只能分配给一头牛。 问最多能有多少头牛可以同时得到喜欢的食物和饮料。 解析: 由于要同时得到喜欢的食物和饮料,所以网络流建图的时候要把牛拆点了。 如下建图: s -> 食物 -> 牛1 -> 牛2 -> 饮料 -> t 所以分配一下点: s  =  0, 牛1= 1~

poj 3068 有流量限制的最小费用网络流

题意: m条有向边连接了n个仓库,每条边都有一定费用。 将两种危险品从0运到n-1,除了起点和终点外,危险品不能放在一起,也不能走相同的路径。 求最小的费用是多少。 解析: 抽象出一个源点s一个汇点t,源点与0相连,费用为0,容量为2。 汇点与n - 1相连,费用为0,容量为2。 每条边之间也相连,费用为每条边的费用,容量为1。 建图完毕之后,求一条流量为2的最小费用流就行了

poj 2112 网络流+二分

题意: k台挤奶机,c头牛,每台挤奶机可以挤m头牛。 现在给出每只牛到挤奶机的距离矩阵,求最小化牛的最大路程。 解析: 最大值最小化,最小值最大化,用二分来做。 先求出两点之间的最短距离。 然后二分匹配牛到挤奶机的最大路程,匹配中的判断是在这个最大路程下,是否牛的数量达到c只。 如何求牛的数量呢,用网络流来做。 从源点到牛引一条容量为1的边,然后挤奶机到汇点引一条容量为m的边

配置InfiniBand (IB) 和 RDMA over Converged Ethernet (RoCE) 网络

配置InfiniBand (IB) 和 RDMA over Converged Ethernet (RoCE) 网络 服务器端配置 在服务器端,你需要确保安装了必要的驱动程序和软件包,并且正确配置了网络接口。 安装 OFED 首先,安装 Open Fabrics Enterprise Distribution (OFED),它包含了 InfiniBand 所需的驱动程序和库。 sudo

【机器学习】高斯网络的基本概念和应用领域

引言 高斯网络(Gaussian Network)通常指的是一个概率图模型,其中所有的随机变量(或节点)都遵循高斯分布 文章目录 引言一、高斯网络(Gaussian Network)1.1 高斯过程(Gaussian Process)1.2 高斯混合模型(Gaussian Mixture Model)1.3 应用1.4 总结 二、高斯网络的应用2.1 机器学习2.2 统计学2.3