【鸿蒙开发实战】HarmonyOS网络请求简化示例

使用说明

  1. 创建文件

    • entry/src/main/ets/pages/ 目录下创建 NetworkDemo.ets

    • 或者直接替换现有页面的代码

  2. 配置权限

    • module.json5 中添加网络权限(如上所示)
  3. 运行应用

    • 点击"测试GET请求"按钮发送HTTP请求

    • 点击"检查网络状态"测试网络连通性

    • 点击"清除数据"清空显示内容

核心功能说明

  1. 网络请求 :使用 @ohos.net.http 模块发送HTTP GET请求

  2. 状态管理 :使用 @State 装饰器管理UI状态

  3. 异步处理 :使用 async/await 处理异步网络请求

  4. 错误处理:完整的异常捕获和处理机制

  5. UI反馈:加载状态提示和结果显示

部分代码

复制代码
// NetworkDemo.ets - HarmonyOS网络功能示例
import http from '@ohos.net.http';
import common from '@ohos.app.ability.common';
import { BusinessError } from '@ohos.base';

// 定义Http请求选项的接口
interface HttpRequestOptions {
  method: http.RequestMethod;
  header?: Record<string, string>;
  connectTimeout?: number;
  readTimeout?: number;
  extraData?: string | Object;
}

// 定义API响应数据结构
interface ApiResponse {
  userId: number;
  id: number;
  title: string;
  body: string;
}

// 定义错误信息数据结构
interface ErrorInfo {
  code?: number;
  message?: string;
  stack?: string;
  name?: string;
}

@Entry
@Component
struct NetworkDemo {
  @State message: string = '点击按钮测试网络连接';
  @State responseData: string = '';
  @State isConnected: boolean = false;
  
  // 获取Ability上下文
  private context = getContext(this) as common.UIAbilityContext;

  build() {
    Column({ space: 20 }) {
      // 显示状态信息
      Text(this.message)
        .fontSize(20)
        .fontColor(Color.Blue)
        .margin({ top: 30 })

      // 显示连接状态
      Text(this.isConnected ? '网络已连接' : '网络未连接')
        .fontSize(18)
        .fontColor(this.isConnected ? Color.Green : Color.Red)

      // 显示响应数据
      Scroll() {
        Text(this.responseData)
          .fontSize(14)
          .textAlign(TextAlign.Start)
          .padding(10)
      }
      .height(200)
      .width('90%')
      .border({ width: 1, color: Color.Gray })

      // 功能按钮区域
      Column({ space: 15 }) {
        // 测试GET请求
        Button('测试GET请求')
          .width('80%')
          .height(40)
          .onClick(() => {
            this.testGetRequest();
          })

        // 测试连接状态
        Button('检查网络状态')
          .width('80%')
          .height(40)
          .onClick(() => {
            this.checkNetworkStatus();
          })

        // 清除数据
        Button('清除数据')
          .width('80%')
          .height(40)
          .onClick(() => {
            this.clearData();
          })
      }
      .width('100%')
      .margin({ top: 20 })

      // 进度指示器
      LoadingProgress()
        .color(Color.Blue)
        .visibility(this.message.includes('请求中') ? Visibility.Visible : Visibility.Hidden)
    }
    .width('100%')
    .height('100%')
    .padding(20)
    .justifyContent(FlexAlign.Start)
  }

  // 测试GET请求
  private async testGetRequest() {
    this.message = '正在发送请求...';
    this.responseData = '';
    
    try {
      // 创建HTTP请求
      let httpRequest = http.createHttp();
      
      // 设置请求参数 - 使用明确定义的类型
      let url = 'https://jsonplaceholder.typicode.com/posts/1'; // 免费测试API
      let options: HttpRequestOptions = {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json'
        },
        connectTimeout: 60000,
        readTimeout: 60000
      };

      // 发送请求
      let response = await httpRequest.request(url, options);
      
      // 检查响应状态
      if (response.responseCode === 200) {
        this.message = '请求成功!';
        this.isConnected = true;
        
        // 安全地处理响应数据
        try {
          const result = response.result as string;
          const parsedData: ApiResponse = JSON.parse(result) as ApiResponse;
          this.responseData = JSON.stringify(parsedData, null, 2);
        } catch (parseError) {
          this.responseData = response.result as string;
        }
      } else {
        this.message = `请求失败: ${response.responseCode}`;
        this.isConnected = false;
        this.responseData = response.result ? response.result as string : '无响应数据';
      }
      
      // 释放资源
      httpRequest.destroy();
      
    } catch (error) {
      // 使用BusinessError类型处理错误
      const businessError = error as BusinessError;
      this.message = `请求异常: ${businessError.message || '未知错误'}`;
      this.isConnected = false;
      
      // 安全地序列化错误对象 - 使用明确定义的类型
      try {
        const errorObj: ErrorInfo = {
          code: businessError.code,
          message: businessError.message,
          stack: businessError.stack,
          name: 'BusinessError'
        };
        this.responseData = JSON.stringify(errorObj, null, 2);
      } catch (stringifyError) {
        const stringifyErr = stringifyError as Error;
        this.responseData = `错误信息: ${businessError.message || '未知错误'}\n序列化错误: ${stringifyErr.message}`;
      }
    }
  }

  // 检查网络状态
  private async checkNetworkStatus() {
    try {
      // 简单的连接性检查
      let httpRequest = http.createHttp();
      
      // 使用明确定义的类型
      let options: HttpRequestOptions = {
        method: http.RequestMethod.GET,
        connectTimeout: 5000
      };
      
      await httpRequest.request('https://www.baidu.com', options);
      
      this.message = '网络连接正常';
      this.isConnected = true;
      httpRequest.destroy();
      
    } catch (error) {
      const businessError = error as BusinessError;
      this.message = `网络连接失败: ${businessError.message || '请检查网络设置'}`;
      this.isConnected = false;
    }
  }

  // 清除数据
  private clearData() {
    this.responseData = '';
    this.message = '数据已清除,点击按钮测试网络';
  }
}

入门鸿蒙开发又怕花冤枉钱?别错过!现在能免费系统学 -- 从 ArkTS 面向对象核心的类和对象、继承多态,到吃透鸿蒙开发关键技能,还能冲刺鸿蒙基础 +高级开发者证书,更惊喜的是考证成功还送好礼!快加入我的鸿蒙班,一起从入门到精通,班级链接:点击https://developer.huawei.com/consumer/cn/training/classDetail/b7365031334e4353a9a0fd6785bb0791?type=1?ha_source=hmosclass\&ha_sourceId=89000248免费进入

相关推荐
程序猿追3 小时前
那个右下角的小数字怎么“卡”住我打字——我用 HarmonyOS 自己写了一个字数限制输入框
pytorch·华为·harmonyos
古德new3 小时前
鸿蒙PC使用electron迁移:Joplin Electron 桌面适配全记录
华为·electron·harmonyos
世人万千丶3 小时前
桌面便签小应用 - HarmonyOS ArkUI 开发实战-TextArea与Flex布局-PC版本
华为·harmonyos·鸿蒙·鸿蒙系统
慧海灵舟3 小时前
AGenUI 鸿蒙端实战踩坑录:从 Column 布局消失到异步组件宽度为 0
华为·harmonyos
yuegu7773 小时前
HarmonyOS应用<节气通>开发第33篇:状态管理实战
华为·harmonyos
YM52e4 小时前
买菜计算器小应用 - HarmonyOS ArkUI 开发实战-PC版本
学习·华为·harmonyos·鸿蒙·鸿蒙系统
阿捏利4 小时前
系列总览-鸿蒙科普系列完全指南
华为·harmonyos
小雨下雨的雨4 小时前
HarmonyOS ArkUI训练营入门-组件掌握系列-Animation 动画效果实现-PC版本
学习·华为·harmonyos·鸿蒙
yuegu7774 小时前
HarmonyOS应用<节气通>开发第32篇:ArkTS语法快速入门——从TypeScript到声明式UI的完整指南
harmonyos
2601_962072556 小时前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos