HarmonyOS鸿蒙Next中http请求的封装

HarmonyOS鸿蒙Next中http请求的封装 1 自定义请求消息头
2 支持GET和POST
3 将拿到的JSON数据 可以封装转化成对象或者LIST

3 回复

网络请求axios三方库可以支持自定义请求头和转换数据
[@ohos/axios](https://ohpm.openharmony.cn/#/cn/detail/)

更多关于HarmonyOS鸿蒙Next中http请求的封装的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,HTTP请求的封装主要通过@ohos.net.http模块实现。该模块提供了HttpRequest类,用于发起和处理HTTP请求。开发者可以通过创建HttpRequest对象,配置请求参数(如URL、请求方法、头部、请求体等),并调用request方法来发送请求。

示例代码如下:

import http from '@ohos.net.http';

let httpRequest = http.createHttp();
let url = "https://example.com/api/data";
let headers = {
    'Content-Type': 'application/json'
};
let options = {
    method: http.RequestMethod.GET,
    header: headers,
    readTimeout: 5000,
    connectTimeout: 5000
};

httpRequest.request(url, options, (err, data) => {
    if (err) {
        console.error(`Request failed, code is ${err.code}, message is ${err.message}`);
    } else {
        console.info('Request successful:', data.result);
    }
});

HttpRequest类支持多种HTTP方法(如GET、POST等),并允许设置超时时间、请求头等。请求结果通过回调函数返回,包含响应数据或错误信息。

在HarmonyOS鸿蒙Next中,封装HTTP请求可以通过@ohos.net.http模块实现。首先,创建HttpRequest对象,设置URL、请求方法(如GET、POST)、请求头、请求体等。然后,调用request方法发送请求,并通过回调函数处理响应数据。为简化使用,可以封装一个通用方法,传入URL、参数、请求头等,返回Promise对象,便于异步处理。

示例代码如下:

import http from '@ohos.net.http';

async function httpRequest(url, method = 'GET', data = {}, headers = {}) {
    let httpRequest = http.createHttp();
    let options = {
        method: method,
        header: headers,
        extraData: method === 'POST' ? JSON.stringify(data) : ''
    };
    return new Promise((resolve, reject) => {
        httpRequest.request(url, options, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

此封装方法支持GET和POST请求,可根据需要扩展其他HTTP方法。

回到顶部