HarmonyOS ArkTS HTTP 请求简单封装(二十二)

在鸿蒙ArkTs 中进行 HTTP 请求封装可以通过使用 http 模块来实现。以下是一个简单的示例,演示如何在鸿蒙ArkTs 中封装 HTTP 请求:

  • 1、首先,创建一个 HttpUtil.ts 文件,并引入相关模块:
bash 复制代码
import { HttpMethod, Request, Response, sendRequest } from '@ohos-tool/http';
  • 2、编写一个简单的 HTTP 请求封装函数,例如:
bash 复制代码
export async function httpRequest(url: string, method: HttpMethod, data?: any): Promise<any> {
    const request: Request = {
        url: url,
        method: method,
        data: data ? JSON.stringify(data) : undefined,
        header: {
            'Content-Type': 'application/json'
        }
    };

    try {
        const response: Response = await sendRequest(request);
        if (response.statusCode === 200) {
            return JSON.parse(response.data);
        } else {
            console.error(`HTTP request failed with status code: ${response.statusCode}`);
            return null;
        }
    } catch (error) {
        console.error(`An error occurred during the HTTP request: ${error}`);
        return null;
    }
}

在这个示例中,我们定义了一个 httpRequest 函数,接收 URL、HTTP 方法和可选的数据作为参数。函数会将请求发送到指定的 URL,并返回响应数据(如果请求成功的话)。

  • 3、在其他文件中使用这个封装好的 HTTP 请求函数,例如:
bash 复制代码
import { HttpMethod } from '@ohos-tool/http';
import { httpRequest } from './HttpUtil';

async function fetchData() {
    const url = 'https://jsonplaceholder.typicode.com/posts/1';
    const method = HttpMethod.GET;

    const response = await httpRequest(url, method);
    if (response) {
        console.log(response);
    } else {
        console.log('Failed to fetch data');
    }
}

fetchData();

在这个示例中,我们导入了 httpRequest 函数并使用它来发送一个 GET 请求,然后打印响应数据或错误消息。

请确保在项目中添加对应的依赖库,以及在 config.json 中配置 TypeScript 编译选项,确保项目能够正确编译并运行。这只是一个简单的示例,你可以根据实际需求对 HTTP 请求封装进行更复杂的处理。

相关推荐
二流小码农1 小时前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
万少11 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
Huang兄1 天前
鸿蒙-List和Grid拖拽排序:仿微信小程序删除效果
harmonyos·arkts·arkui
anyup2 天前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
不可能的是2 天前
前端 SSE 流式请求三种实现方案全解析
前端·http
Ranger09292 天前
鸿蒙开发新范式:Gpui
rust·harmonyos
Huang兄2 天前
鸿蒙-深色模式适配
harmonyos·arkts·arkui
SummerKaze4 天前
为鸿蒙开发者写一个 nvm:hmvm 的设计与实现
harmonyos
在人间耕耘6 天前
HarmonyOS Vision Kit 视觉AI实战:把官方 Demo 改造成一套能长期复用的组件库
人工智能·深度学习·harmonyos
王码码20356 天前
Flutter for OpenHarmony:socket_io_client 实时通信的事实标准(Node.js 后端的最佳拍档) 深度解析与鸿蒙适配指南
android·flutter·ui·华为·node.js·harmonyos