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

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

 相关链接:

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

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

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

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

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

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

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

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

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

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

 推荐链接:

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

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

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

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

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

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

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

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

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

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

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

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

推荐链接:

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

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

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

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

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

本章内容主要是通过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 });
        }
      }
    );
  }
}

三、最终效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值