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


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

    • 1、首先,创建一个 HttpUtil.ts 文件,并引入相关模块:
    import { HttpMethod, Request, Response, sendRequest } from '@ohos-tool/http';
    
    • 1
    • 2、编写一个简单的 HTTP 请求封装函数,例如:
    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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

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

    • 3、在其他文件中使用这个封装好的 HTTP 请求函数,例如:
    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();
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

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

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

  • 相关阅读:
    牛客: BM5 合并k个已排序的链表
    解决from d2l import torch as d2l报pandas,numpy的相关问题
    C语言 指针进阶 贰
    oracle21c安装报错【[INS-32014] 指定的 Oracle 基目录位置XXX无效】
    andriodstudio创建不了项目,如何解决?
    Gopher的Rust第一课:第一个Rust程序
    Shopee买家号有什么作用?如何才能拥有大量的虾皮买家号?
    android 静默升级 卸载功能实现
    理解linux进程
    C++17新特性的使用场景总结
  • 原文地址:https://blog.csdn.net/Chen_xiaobao/article/details/136656453