HarmonyOS 鸿蒙Next HTTP请求组件

发布于 1周前 作者 sinazl 来自 鸿蒙OS

HarmonyOS 鸿蒙Next HTTP请求组件

http请求组件http请求组件
 

2 回复

可以参考以下示例:

深色代码主题
复制
import axios, { AxiosResponse, FormData, InternalAxiosRequestConfig } from '[@ohos](/user/ohos)/axios';
import fs from '[@ohos](/user/ohos).file.fs';

export class AxiosUtil { private static instance: AxiosUtil = new AxiosUtil() interceptorId: number = 0

private constructor() { this.interceptorId = axios.interceptors.request.use((config: InternalAxiosRequestConfig) => { config.headers[‘Content-Type’] = ‘application/json’ return config }) }

public static getInstance(url: string) { AxiosUtil.instance.create(url) return AxiosUtil.instance }

// axios: AxiosInstance create(baseUrl?: string): Result { axios.defaults.baseURL = baseUrl console.log(axios.defaults.baseURL) return { currentBaseUrl: baseUrl } }

async request(url: string): Promise<Result> { let result: Result = {} let res: AxiosResponse = await axios.request({ url: url, method: ‘get’ }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async post<T = undefined>(url: string, data?: T): Promise<Result> { let result: Result = {} let res: AxiosResponse = await axios.post<string, AxiosResponse<string>, T>(url, data === undefined ? null : data) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async get(url: string): Promise<Result> { let result: Result = {} let res: AxiosResponse = await axios.get<string, AxiosResponse<string>, null>(url) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async put<T = undefined>(url: string, data?: T): Promise<Result> { let result: Result = {} let res: AxiosResponse | void = await axios.put<string, AxiosResponse<string>, T>(url, data === undefined ? null : data) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async delete<T = undefined>(url: string, data?: T): Promise<Result> { let result: Result = {} let res: AxiosResponse | void = await axios.delete<string, AxiosResponse<string>, T>(url, data === undefined ? null : { data: data }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async download(url: string, filePath: string) { // 如果文件已存在则先删除 if (fs.accessSync(filePath)) { fs.unlinkSync(filePath); } let result: Result = {} let res: AxiosResponse = await axios<string, AxiosResponse<string>, null>({ url: url, method: ‘get’, context: getContext(this), filePath: filePath }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async upload(url: string, filePath: string, fileName: string): Promise<Result> { let formData = new FormData() let result: Result = {} try { let file = fs.openSync(filePath, 0o2); let state = fs.lstatSync(filePath) let buffer = new ArrayBuffer(state.size) fs.readSync(file.fd, buffer); fs.closeSync(file.fd); formData.append(‘file’, buffer); formData.append(‘name’, fileName) } catch (err) { console.log(‘err’ + JSON.stringify(err)) } let res: AxiosResponse = await axios.post<string, AxiosResponse<string>, FormData>(url, formData, { headers: { ‘Content-Type’: ‘multipart/form-data’ }, context: getContext(this), }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result } }

export interface InfoModel { id: number name: string briefDesc: string author: string licence: string gitUrl: string keyword: string }

export interface Demo_config { baseUrl: string, getUrl: string, postUrl: string, putUrl: string, deleteUrl: string, downloadUrl: string, uploadUrl: string, clientCert_noPsw: string, clientCert_hasPsw: string, proxyUrl: string, host: string, psw: string, }

export interface Result { // currentBaseUrl 当前BaseUrl currentBaseUrl?: string, // status 来自服务器响应的 HTTP 状态码 statue?: string // data 由服务器提供的响应 data?: string // statusText 来自服务器响应的 HTTP 状态信息 statusText?: string, }import axios, { AxiosResponse, FormData, InternalAxiosRequestConfig } from @ohos/axios’; import fs from @ohos.file.fs’;

export class AxiosUtil { private static instance: AxiosUtil = new AxiosUtil() interceptorId: number = 0

private constructor() { this.interceptorId = axios.interceptors.request.use((config: InternalAxiosRequestConfig) => { config.headers[‘Content-Type’] = ‘application/json’ return config }) }

public static getInstance(url: string) { AxiosUtil.instance.create(url) return AxiosUtil.instance }

// axios: AxiosInstance create(baseUrl?: string): Result { axios.defaults.baseURL = baseUrl console.log(axios.defaults.baseURL) return { currentBaseUrl: baseUrl } }

async request(url: string): Promise<Result> { let result: Result = {} let res: AxiosResponse = await axios.request({ url: url, method: ‘get’ }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async post<T = undefined>(url: string, data?: T): Promise<Result> { let result: Result = {} let res: AxiosResponse = await axios.post<string, AxiosResponse<string>, T>(url, data === undefined ? null : data) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async get(url: string): Promise<Result> { let result: Result = {} let res: AxiosResponse = await axios.get<string, AxiosResponse<string>, null>(url) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async put<T = undefined>(url: string, data?: T): Promise<Result> { let result: Result = {} let res: AxiosResponse | void = await axios.put<string, AxiosResponse<string>, T>(url, data === undefined ? null : data) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async delete<T = undefined>(url: string, data?: T): Promise<Result> { let result: Result = {} let res: AxiosResponse | void = await axios.delete<string, AxiosResponse<string>, T>(url, data === undefined ? null : { data: data }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async download(url: string, filePath: string) { // 如果文件已存在则先删除 if (fs.accessSync(filePath)) { fs.unlinkSync(filePath); } let result: Result = {} let res: AxiosResponse = await axios<string, AxiosResponse<string>, null>({ url: url, method: ‘get’, context: getContext(this), filePath: filePath }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result }

async upload(url: string, filePath: string, fileName: string): Promise<Result> { let formData = new FormData() let result: Result = {} try { let file = fs.openSync(filePath, 0o2); let state = fs.lstatSync(filePath) let buffer = new ArrayBuffer(state.size) fs.readSync(file.fd, buffer); fs.closeSync(file.fd); formData.append(‘file’, buffer); formData.append(‘name’, fileName) } catch (err) { console.log(‘err’ + JSON.stringify(err)) } let res: AxiosResponse = await axios.post<string, AxiosResponse<string>, FormData>(url, formData, { headers: { ‘Content-Type’: ‘multipart/form-data’ }, context: getContext(this), }) result.statue = res ? JSON.stringify(res.status) : ‘’; result.data = res ? JSON.stringify(res.data) : ‘’; result.statusText = res ? res.statusText : ‘’; return result } }

export interface InfoModel { id: number name: string briefDesc: string author: string licence: string gitUrl: string keyword: string }

export interface Demo_config { baseUrl: string, getUrl: string, postUrl: string, putUrl: string, deleteUrl: string, downloadUrl: string, uploadUrl: string, clientCert_noPsw: string, clientCert_hasPsw: string, proxyUrl: string, host: string, psw: string, }

export interface Result { // currentBaseUrl 当前BaseUrl currentBaseUrl?: string, // status 来自服务器响应的 HTTP 状态码 statue?: string // data 由服务器提供的响应 data?: string // statusText 来自服务器响应的 HTTP 状态信息 statusText?: string, }

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


在HarmonyOS鸿蒙Next中,HTTP请求组件通常用于实现网络数据的请求与接收。鸿蒙系统提供了丰富的网络API,可用于构建HTTP客户端,进行GET、POST等请求操作。

要实现HTTP请求,你可以使用ohos.network.http.HttpRequest类。这个类提供了发送HTTP请求的方法,并允许你设置请求头、请求体等参数。以下是一个基本的HTTP GET请求示例:

import ohos.network.http.HttpRequest;
import ohos.network.http.HttpResponse;

function sendGetRequest(url) {
    let request = new HttpRequest();
    request.method = HttpRequest.GET;
    request.url = url;

    request.send((err, response) => {
        if (err) {
            console.error('Request failed:', err);
        } else {
            console.log('Response received:', response.code, response.data);
        }
    });
}

对于POST请求,你需要设置请求方法为POST,并可能需要设置请求体。示例如下:

function sendPostRequest(url, data) {
    let request = new HttpRequest();
    request.method = HttpRequest.POST;
    request.url = url;
    request.header = {"Content-Type": "application/json"};
    request.sendData = JSON.stringify(data);

    request.send((err, response) => {
        // 处理响应
    });
}

这些示例展示了如何在鸿蒙系统中进行基本的HTTP请求。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html

回到顶部