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

相关推荐
梦想不只是梦与想5 小时前
鸿蒙 AI自动化测试实现
单元测试·harmonyos·hypium
用户09340777351412 小时前
HarmonyOS WPS Open SDK 工程实践:把 registerApp 做成就绪门禁
typescript·harmonyos
大雷神14 小时前
HarmonyOS7应用《拼棋派对》实战:双人键盘操作与窗口焦点恢复
harmonyos·arkui·harmonyos 7.0·玩转 arkts
2501_9462447816 小时前
开源鸿蒙平台 CMP 三方库「compose-continuous-rounded-corner-shape」适配全流程
华为·开源·harmonyos
KevinChaos16 小时前
灶台菜谱设计手记 03|HarmonyOS 7.0 空间化:沉浸光感反馈
harmonyos
大雷神17 小时前
HarmonyOS7应用《拼棋派对》实战:折叠屏与电脑的窗口布局适配
harmonyos·arkui·harmonyos 7.0·玩转 arkts
2501_9462447817 小时前
开源鸿蒙平台 CMP 三方库「Waterfall」适配全流程
华为·开源·harmonyos
2401_zq136y0317 小时前
开源鸿蒙平台 CMP 三方库「Jewel」适配全流程
华为·开源·harmonyos
2601_9494800618 小时前
开源鸿蒙平台 KMP 三方库「AutoLinkText」适配全流程
华为·开源·harmonyos
JoyCong199818 小时前
ToDesk鸿蒙PC端又焕新!远控更稳、操作更准,跨端办公如本地
运维·华为·智能手机·harmonyos·远程工作