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 请求封装进行更复杂的处理。

相关推荐
ysu_03146 分钟前
Postman接口调试实战指南-从HTTP请求到环境变量-Collection与自动化测试
网络·网络协议·测试工具·http·api·postman·可用性测试
吴声子夜歌1 小时前
Nginx应用与运维——Nginx HTTP模块详解(访问控制功能模块)
运维·nginx·http
zhangfeng11333 小时前
Reward Hacking 奖励钻空子 / 奖励作弊 Specification Gaming(规范博弈)
人工智能·华为·ai编程·npu
特立独行的猫a5 小时前
用仓颉写一个 Tauri:IPC 的每次往返实现原理(web层到仓颉层的触发过程)
前端·ui·harmonyos·tauri·鸿蒙·仓颉
2501_919749035 小时前
华为鸿蒙桌面时钟与悬浮时钟APP—小羊时钟
华为·harmonyos
wuyk5556 小时前
Python网络爬虫入门到实战 第02章:HTTP/HTTPS协议超通俗精讲(GET/POST、请求头、响应码、爬虫核心基础)
爬虫·python·http
HwJack206 小时前
【共创稿事节】HarmonyOS 7空间交互综述:视线、头部、手势的协同
数码相机·交互·harmonyos
李游Leo7 小时前
HarmonyOS 7 ArkUI + Window Kit:折叠屏编辑页的键盘避让快照与焦点恢复时序【鸿蒙心迹】
华为·计算机外设·harmonyos
傲世仙尊7 小时前
HTTP深水区-重定向状态码与GETPOST的传参之路
网络·网络协议·http
李游Leo8 小时前
HarmonyOS 7 HSP + Localization Kit:共享组件资源导出、语言回退与相对路径失效诊断【鸿蒙心迹】
harmonyos