【鸿蒙开发实战】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免费进入

相关推荐
小雨下雨的雨6 小时前
Flutter 框架跨平台鸿蒙开发 —— SingleChildScrollView 控件之长内容滚动艺术
flutter·ui·华为·harmonyos·鸿蒙
2501_944521007 小时前
rn_for_openharmony商城项目app实战-商品评价实现
javascript·数据库·react native·react.js·ecmascript·harmonyos
lili-felicity7 小时前
React Native for Harmony 企业级 Grid 宫格组件 完整实现
react native·react.js·harmonyos
以太浮标8 小时前
华为eNSP模拟器综合实验之- VLAN聚合(VLAN Aggregation或Super VLAN)解析
运维·网络·华为·信息与通信
lili-felicity9 小时前
React Native 鸿蒙跨平台开发:动态表单全场景实现
react native·harmonyos
奋斗的小青年!!9 小时前
Flutter跨平台开发适配OpenHarmony:文件系统操作深度实践
flutter·harmonyos·鸿蒙
SunkingYang10 小时前
从硬件参数、系统等方面详细对比华为mate80 pro max与iPhone17 pro max
华为·苹果·iphone17·mate80·promax·手机对比
奋斗的小青年!!10 小时前
Flutter跨平台开发OpenHarmony应用:个人中心实现
开发语言·前端·flutter·harmonyos·鸿蒙
人工智能知识库11 小时前
2026年HCCDP-GaussDB工作级开发者题库(详细解析)
数据库·华为·gaussdb·题库·hccdp-gaussdb·工作级开发者认证
IT=>小脑虎12 小时前
鸿蒙开发零基础小白学习知识点【基础版·详细版】
学习·华为·harmonyos