开源 Arkts 鸿蒙应用 开发(十)通讯--Http数据传输

 文章的目的为了记录使用Arkts 进行Harmony app 开发学习的经历。本职为嵌入式软件开发,公司安排开发app,临时学习,完成app的开发。开发流程和要点有些记忆模糊,赶紧记录,防止忘记。

 相关链接:

开源 Arkts 鸿蒙应用 开发(一)工程文件分析-CSDN博客

开源 Arkts 鸿蒙应用 开发(二)封装库.har制作和应用-CSDN博客

开源 Arkts 鸿蒙应用 开发(三)Arkts的介绍-CSDN博客

开源 Arkts 鸿蒙应用 开发(四)布局和常用控件-CSDN博客

开源 Arkts 鸿蒙应用 开发(五)控件组成和复杂控件-CSDN博客

开源 Arkts 鸿蒙应用 开发(六)数据持久--文件和首选项存储-CSDN博客

开源 Arkts 鸿蒙应用 开发(七)数据持久--sqlite关系数据库-CSDN博客

开源 Arkts 鸿蒙应用 开发(八)多媒体--相册和相机-CSDN博客

开源 Arkts 鸿蒙应用 开发(九)通讯--tcp客户端-CSDN博客

开源 Arkts 鸿蒙应用 开发(十)通讯--Http-CSDN博客

 推荐链接:

开源 java android app 开发(一)开发环境的搭建-CSDN博客

开源 java android app 开发(二)工程文件结构-CSDN博客

开源 java android app 开发(三)GUI界面布局和常用组件-CSDN博客

开源 java android app 开发(四)GUI界面重要组件-CSDN博客

开源 java android app 开发(五)文件和数据库存储-CSDN博客

开源 java android app 开发(六)多媒体使用-CSDN博客

开源 java android app 开发(七)通讯之Tcp和Http-CSDN博客

开源 java android app 开发(八)通讯之Mqtt和Ble-CSDN博客

开源 java android app 开发(九)后台之线程和服务-CSDN博客

开源 java android app 开发(十)广播机制-CSDN博客

开源 java android app 开发(十一)调试、发布-CSDN博客

开源 java android app 开发(十二)封库.aar-CSDN博客

推荐链接:

开源C# .net mvc 开发(一)WEB搭建_c#部署web程序-CSDN博客

开源 C# .net mvc 开发(二)网站快速搭建_c#网站开发-CSDN博客

开源 C# .net mvc 开发(三)WEB内外网访问(VS发布、IIS配置网站、花生壳外网穿刺访问)_c# mvc 域名下不可訪問內網,內網下可以訪問域名-CSDN博客

开源 C# .net mvc 开发(四)工程结构、页面提交以及显示_c#工程结构-CSDN博客

https://blog.csdn.net/ajassi2000/article/details/149584283?spm=1011.2124.3001.6209开源 C# .net mvc 开发(五)常用代码快速开发_c# mvc开发-CSDN博客

本章内容主要是通过Http访问web网站,获得天气的Json数据,进行解析的功能。将访问的页面地址进行修改,添加id和key则可以访问网站的Api,实现高级功能。

一、添加权限,与上个章节相同,在module.json5的最后添加上以下代码

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

二、Index.ets代码分析

2.1  界面代码

2个Text,1个显示Http的返回,1个显示json数据

以下为代码

 build() {Column() {// 显示获取到的网页内容Scroll() {Column() {Text(this.responseData).fontSize(16).width('100%').textAlign(TextAlign.Start).padding(10)// 添加天气信息显示区域if (this.weatherInfo) {Divider().margin(10)Text('解析后的天气数据:').fontSize(18).fontWeight(FontWeight.Bold).margin({ bottom: 10 })Text(`城市: ${this.weatherInfo.city}`).fontSize(16).margin({ bottom: 5 })Text(`温度: ${this.weatherInfo.temp}°C`).fontSize(16).margin({ bottom: 5 })Text(`风向: ${this.weatherInfo.WD}`).fontSize(16).margin({ bottom: 5 })Text(`风力: ${this.weatherInfo.WS}`).fontSize(16).margin({ bottom: 5 })Text(`湿度: ${this.weatherInfo.SD}`).fontSize(16).margin({ bottom: 5 })Text(`气压: ${this.weatherInfo.qy} hPa`).fontSize(16).margin({ bottom: 5 })Text(`更新时间: ${this.weatherInfo.time}`).fontSize(16).margin({ bottom: 5 })}}.width('100%')}.height('80%').width('100%')// 请求按钮Button('获取天气数据').width('80%').height(50).margin(20).onClick(() => {this.fetchWeatherData();})}.width('100%').height('100%')

2.2  Json数据结构

天气数据

以下为代码

// 定义天气信息的接口类型
interface WeatherInfo {city: string;cityid: string;temp: string;WD: string;WS: string;SD: string;WSE: string;time: string;isRadar: string;Radar: string;njd: string;qy: string;rain: string;
}interface WeatherResponse {weatherinfo: WeatherInfo;
}

2.3  fetchWeatherData()方法:
创建HTTP请求,http.createHttp()
发送GET请求到天气API,httpRequest.request()
成功时解析JSON并更新UI

以下为代码

 // 发起HTTP请求private fetchWeatherData() {let httpRequest = http.createHttp();this.responseData = '正在请求数据...';this.weatherInfo = null;httpRequest.request('https://www.weather.com.cn/data/sk/101010100.html',{method: http.RequestMethod.GET,header: {'Content-Type': 'application/json'}},(err, data) => {if (err) {this.responseData = `请求失败: ${JSON.stringify(err)}`;promptAction.showToast({ message: '请求失败', duration: 2000 });return;}if (data.responseCode === 200) {try {const result: WeatherResponse = JSON.parse(data.result.toString());//this.responseData = `HTTP状态码: ${data.responseCode}\n\n原始JSON数据:\n${JSON.stringify(result, null, 2)}`;this.responseData = data.result.toString();if (result.weatherinfo) {this.weatherInfo = result.weatherinfo;}promptAction.showToast({ message: '获取并解析成功', duration: 2000 });} catch (e) {this.responseData = `JSON解析失败: ${e.message}\n\n原始数据:\n${data.result}`;promptAction.showToast({ message: 'JSON解析失败', duration: 2000 });}} else {this.responseData = `请求异常: HTTP状态码 ${data.responseCode}`;promptAction.showToast({ message: '请求异常', duration: 2000 });}});}

2.4  网络API的使用

网上有各种网络API,通常的方式是访问地址和id以及key,通过注册可以获得id和key,访问网址就可以获得输入,比如https://xxx/now?&id=CN101010100&key=xxxxx

关键流程:创建HTTP实例, 发起GET请求,处理响应(HTTP状态码非200为出错需要处理)

https://www.weather.com.cn/data/sk/101010100.html地址页面图片

下面为代码

import http from '@ohos.net.http';
import promptAction from '@ohos.promptAction';
import webview from '@ohos.web.webview';// 定义天气信息的接口类型
interface WeatherInfo {city: string;cityid: string;temp: string;WD: string;WS: string;SD: string;WSE: string;time: string;isRadar: string;Radar: string;njd: string;qy: string;rain: string;
}interface WeatherResponse {weatherinfo: WeatherInfo;
}@Entry
@Component
struct HttpExample {@State responseData: string = '等待获取数据...';@State webController: webview.WebviewController = new webview.WebviewController();@State weatherInfo: WeatherInfo | null = null;build() {Column() {// 显示获取到的网页内容Scroll() {Column() {Text(this.responseData).fontSize(16).width('100%').textAlign(TextAlign.Start).padding(10)// 添加天气信息显示区域if (this.weatherInfo) {Divider().margin(10)Text('解析后的天气数据:').fontSize(18).fontWeight(FontWeight.Bold).margin({ bottom: 10 })Text(`城市: ${this.weatherInfo.city}`).fontSize(16).margin({ bottom: 5 })Text(`温度: ${this.weatherInfo.temp}°C`).fontSize(16).margin({ bottom: 5 })Text(`风向: ${this.weatherInfo.WD}`).fontSize(16).margin({ bottom: 5 })Text(`风力: ${this.weatherInfo.WS}`).fontSize(16).margin({ bottom: 5 })Text(`湿度: ${this.weatherInfo.SD}`).fontSize(16).margin({ bottom: 5 })Text(`气压: ${this.weatherInfo.qy} hPa`).fontSize(16).margin({ bottom: 5 })Text(`更新时间: ${this.weatherInfo.time}`).fontSize(16).margin({ bottom: 5 })}}.width('100%')}.height('80%').width('100%')// 请求按钮Button('获取天气数据').width('80%').height(50).margin(20).onClick(() => {this.fetchWeatherData();})}.width('100%').height('100%')}// 发起HTTP请求private fetchWeatherData() {let httpRequest = http.createHttp();this.responseData = '正在请求数据...';this.weatherInfo = null;httpRequest.request('https://www.weather.com.cn/data/sk/101010100.html',{method: http.RequestMethod.GET,header: {'Content-Type': 'application/json'}},(err, data) => {if (err) {this.responseData = `请求失败: ${JSON.stringify(err)}`;promptAction.showToast({ message: '请求失败', duration: 2000 });return;}if (data.responseCode === 200) {try {const result: WeatherResponse = JSON.parse(data.result.toString());//this.responseData = `HTTP状态码: ${data.responseCode}\n\n原始JSON数据:\n${JSON.stringify(result, null, 2)}`;this.responseData = data.result.toString();if (result.weatherinfo) {this.weatherInfo = result.weatherinfo;}promptAction.showToast({ message: '获取并解析成功', duration: 2000 });} catch (e) {this.responseData = `JSON解析失败: ${e.message}\n\n原始数据:\n${data.result}`;promptAction.showToast({ message: 'JSON解析失败', duration: 2000 });}} else {this.responseData = `请求异常: HTTP状态码 ${data.responseCode}`;promptAction.showToast({ message: '请求异常', duration: 2000 });}});}
}

三、最终效果

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/93184.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/93184.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

net8.0一键创建支持(RabbitMQ)

Necore项目生成器 - 在线创建Necore模板项目 | 一键下载 RabbitMQController.cs using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System.Text; using System.Threading.Tasks; using UnT.Tem…

Rust 泛型与特性

Rust 泛型与特性 引言 Rust 语言以其安全性和高效性在编程语言中独树一帜。Rust 的泛型和特性是其核心特性之一,它们使得开发者能够编写更加通用、灵活且安全的代码。本文将深入探讨 Rust 中的泛型和特性,包括其概念、用法以及在实际开发中的应用。 泛型简介 概念 泛型是…

LangChain学习——结构化输出和数据解析

LangChain 本指南全面介绍LangChain中结构化输出生成和数据解析的核心功能,包括Pydantic BaseModel构造、各种输出解析器的使用,以及高级错误处理机制。 详细测试样例和代码可参考如下两个链接: test_output_parserstest_pydantic_base_mo…

基于华为ENSP的BGP的状态机深入浅出

本篇技术博文摘要 🌟 本文章主要探讨BGP状态机如何控制BGP连接的建立与维护,以及BGP协议在运行过程中如何交换路由信息并确保网络的稳定性 引言 📘 在这个快速发展的技术时代,与时俱进是每个IT人的必修课。我是肾透侧视攻城狮&…

Android 15中的16KB大页有何优势?

deepseek回答: Android 15引入的16KB大内存页是系统性能优化的关键变革,其核心优势体现在以下方面: ⚡ 一、性能全面提升 系统整体加速 配置16KB页面的设备整体性能提升5%-10%,通过减少内存管理开销释放更多资源用于应用运行。…

Gis数据的A*算法规划航线

1.1 用到的技术栈geotools JTSJgrapht1.2 实现思路// 定义栅格网格参数private static final double CELL_SIZE_DEGREES 0.005;private static int gridWidth 0;//格子高度 index 1private static int gridHeight 0;//格子宽度// 1. 读取GeoJSON文件File geoJsonFile new …

Spring Boot 默认使用 CGLIB,但CGLIB 无法代理 final 类或 final 方法

那么当这两件事冲突时,Spring Boot 是怎么“解决”的呢?答案是:它不解决,也无法解决。当这种情况发生时,你的应用程序会直接启动失败。这不是 Spring Boot 的疏忽,而是由 CGLIB 的底层原理和 Java 语言的规…

cuda编程笔记(10)--memory access 优化

全局内存访问优化(Coalesced Access) 什么是 Coalesced Access? 定义:一个 warp(32 个线程)在同一指令中访问全局内存时,如果这些访问请求可以合并成尽可能少的内存事务(通常是 32…

闲庭信步使用图像验证平台加速FPGA的开发:第三十一课——车牌识别的FPGA实现(3)车牌字符分割预处理

(本系列只需要modelsim即可完成数字图像的处理,每个工程都搭建了全自动化的仿真环境,只需要双击top_tb.bat文件就可以完成整个的仿真,大大降低了初学者的门槛!!!!如需要该系列的工程…

电子电气架构 --- 汽车软件全生命周期

我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 简单,单纯,喜欢独处,独来独往,不易合同频过着接地气的生活,除了生存温饱问题之外,没有什么过多的欲望,表面看起来很高冷,内心热情,如果你身…

力扣面试150(41/150)

7.25 56. 合并区间 以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。 我的思路: 左端点升序…

【隧道篇 / IPsec】(7.6) ❀ 01. 利用向导快速建立IPsec安全隧道 (点对点) ❀ FortiGate 防火墙

【简介】相信很多人已经习惯利用导向快速创建VPN了,而且已经有部分尝鲜者已经用上了FortiOS 7.6,但是会发现FortiOS 7.6下的VPN向导改变了很多,一时无法下手,下面我们来看看最常见的点对点是如何配置的。环境介绍在配置IPsec VPN之…

PLLIP核

。1 号红色框内的速度等级代表着设备的速度 等级,保存默认就好;2 号红色框内设置输入频率;3 号红色框选择 PLL 的工作模式。我们 开发板用的晶振是 50MHz 的,故在 2 号红色框内我们填写 50MHz;我们在 3 号红色框内选正…

1.1 Deep learning?pytorch ?深度学习训练出来的模型通常有效但无法解释合理性? 如何 解释?

DL 是什么,你如何理解DL模型? DL 对于我而言,就是人类试图想通过数学语言描述人类学习过程的一门技术,或者说学科。 因此 DL 模型 相当于 数学 的 一个 funciton ,有输入,通过function处理,得…

java实现在工具类中注入其他对象方式

方案1: Slf4j Component public class ChatdocApiClient {Value("${chatdoc.app-id}")private String appId;Value("${chatdoc.secret}")private String secret;Value("${chatdoc.domain}")private String domain;private final Rest…

electron中IPC 渲染进程与主进程通信方法解析

electron中ipcRenderer.invoke、ipcRenderer.on、ipcRenderer.send、ipcRenderer.sendSync作用与区别 IPC 渲染进程与主进程通信方法解析 ipcRenderer 的这几个方法作用不完全相同,它们适用于不同的通信场景,核心区别在于通信方向、是否需要响应以及同步…

epoll_event 事件类型详解

epoll_event 事件类型详解 epoll_event 是 Linux epoll I/O 多路复用机制的核心结构体&#xff0c;其中的事件类型决定了 epoll 监控的行为和触发条件。以下是各种事件类型的详细解析&#xff1a; epoll_event 结构体 #include <sys/epoll.h>typedef union epoll_data {v…

设计自己的小传输协议 导论与概念

设计自己的小传输协议 导论与概念 1&#xff1a;聊一聊协议头设计 ​ 早在《TCP/IP详解》中的第一句话中&#xff0c;我们就知道协议的含义是这样的&#xff1a;协议是通信双方共同遵守的一套规则&#xff0c;提供格式定义、语义解释等&#xff0c;使不同设备或软件能够正确交…

iOS —— 天气预报仿写总结

在iOS中&#xff0c;最常见的网络请求方式是NSURLSession&#xff0c;它是苹果推荐的现代API&#xff0c;简单安全且易于拓展。一次完整的网络请求流程&#xff1a;构造 NSURL 对象创建 NSURLSessionDataTask发起请求&#xff08;resume&#xff09;在回调中解析数据回到主线程…

MySQL 8.4 Windows 版安装记录与步骤参考

导语&#xff1a; MySQL 作为广泛使用的开源数据库管理系统&#xff0c;是许多开发者和学习者的必备工具。最近有朋友询问安装过程&#xff0c;正好整理了 MySQL 8.4 在 Windows 系统下的安装步骤和一些注意事项&#xff0c;分享给有需要的朋友做个参考。关于 MySQL&#xff1a…