在鸿蒙(HarmonyOS 5)中使用 DevEco Studio 实现小说请求功能,可以通过网络请求获取小说数据并展示。以下是详细步骤和代码示例:

​1. 环境准备​

  • ​DevEco Studio​​:确保安装最新版本(支持HarmonyOS 5)。
  • ​项目配置​​:创建一个 Empty Ability 项目,选择 Stage 模型。
  • ​权限申请​​:在 module.json5 中声明网络权限:
    {
      "module": {
        "requestPermissions": [
          {
            "name": "ohos.permission.INTERNET",
            "reason": "用于请求小说数据"
          }
        ]
      }
    }

​2. 实现网络请求​

HarmonyOS 提供了 @ohos.net.http 模块进行网络请求。以下是封装网络请求的工具类:

​(1)创建 HttpUtil.ts 工具类​
// utils/HttpUtil.ts
import http from '@ohos.net.http';

export class HttpUtil {
  static async get(url: string): Promise<string> {
    return new Promise((resolve, reject) => {
      let httpRequest = http.createHttp();
      httpRequest.request(
        url,
        {
          method: http.RequestMethod.GET,
          connectTimeout: 60000,
          readTimeout: 60000,
        },
        (err, data) => {
          if (err) {
            console.error(`请求失败: ${JSON.stringify(err)}`);
            reject(err);
          } else {
            console.info(`请求成功: ${data.result}`);
            resolve(data.result as string);
          }
          httpRequest.destroy();
        }
      );
    });
  }
}

​3. 定义小说数据模型​

根据API返回的数据结构,定义TypeScript接口:

​(2)创建 NovelModel.ts
// model/NovelModel.ts
export interface NovelInfo {
  id: string;
  title: string;
  author: string;
  content?: string;
}

// 示例API返回数据格式
export interface NovelApiResponse {
  code: number;
  data: NovelInfo[];
  message: string;
}

​4. 实现小说请求逻辑​

在页面中调用网络请求工具类,获取小说数据并展示。

​(3)修改 Index.ets 页面​
// pages/Index.ets
import { HttpUtil } from '../utils/HttpUtil';
import { NovelInfo, NovelApiResponse } from '../model/NovelModel';

@Entry
@Component
struct Index {
  @State novelList: NovelInfo[] = [];
  @State isLoading: boolean = false;

  // 请求小说数据
  async getNovels() {
    try {
      this.isLoading = true;
      const apiUrl = 'https://example.com/api/novels'; // 替换为实际API地址
      const response = await HttpUtil.get(apiUrl);
      const result: NovelApiResponse = JSON.parse(response);
      if (result.code === 200) {
        this.novelList = result.data;
      }
    } catch (err) {
      console.error(`请求异常: ${JSON.stringify(err)}`);
    } finally {
      this.isLoading = false;
    }
  }

  build() {
    Column() {
      Button('加载小说')
        .onClick(() => this.getNovels())
        .margin(10)

      if (this.isLoading) {
        Progress().width(100).height(100)
      }

      List({ space: 10 }) {
        ForEach(this.novelList, (novel: NovelInfo) => {
          ListItem() {
            Column() {
              Text(novel.title).fontSize(18).fontWeight(FontWeight.Bold)
              Text(`作者: ${novel.author}`).fontSize(14).opacity(0.6)
            }
            .padding(10)
            .width('100%')
          }
          .borderRadius(10)
          .backgroundColor('#FFF')
          .shadow({ radius: 2, color: '#AAA', offsetX: 1, offsetY: 1 })
        })
      }
      .width('100%')
      .layoutWeight(1)
    }
    .width('100%')
    .height('100%')
    .padding(12)
    .backgroundColor('#F5F5F5')
  }
}

​5. 关键点说明​

  1. ​权限控制​​:
    • 必须在 module.json5 中声明 ohos.permission.INTERNET 权限。
  2. ​异步处理​​:
    • 使用 Promiseasync/await 处理异步请求,避免阻塞UI。
  3. ​数据绑定​​:
    • 通过 @State 装饰器实现数据变化自动刷新UI。
  4. ​UI优化​​:
    • 添加加载状态(Progress 组件)提升用户体验。

​6. 扩展功能​

  • ​下拉刷新​​:
    使用 Refresh 组件实现:

    @State isRefreshing: boolean = false;
    
    List() {
      // ...
    }
    .onRefresh(() => {
      this.isRefreshing = true;
      this.getNovels().then(() => this.isRefreshing = false);
    })
    .refreshing(this.isRefreshing)
  • ​分页加载​​:
    在API请求中增加 pagepageSize 参数,滚动到底部时触发下一页请求。


​7. 测试数据模拟​

若暂无真实API,可使用以下Mock数据:

// 在 getNovels() 中模拟数据
this.novelList = [
  { id: '1', title: '三体', author: '刘慈欣' },
  { id: '2', title: '活着', author: '余华' }
];
Logo

社区规范:仅讨论OpenHarmony相关问题。

更多推荐