鸿蒙开发中HTTP网络请求_鸿蒙,fetch,patch与put哪个是标准方法
本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新
一、HTTP核心模块对比
@ohos.net.http
@ohos.axios
WebSocket
二、基础HTTP请求
1. GET请求示例
import http from \'@ohos.net.http\';async function fetchData() { // 1. 创建请求对象 let httpRequest = http.createHttp(); // 2. 设置请求参数 let url = \'https://api.example.com/data?id=123\'; let header = { \'Content-Type\': \'application/json\' }; // 3. 发起请求 try { let response = await httpRequest.request( url, { method: \'GET\', header } ); // 4. 处理响应 if (response.responseCode === 200) { console.log(JSON.parse(response.result)); } } catch (err) { console.error(`请求失败: ${err.code}`); } finally { // 5. 销毁请求 httpRequest.destroy(); }}
2. POST请求(带Body)
let options = { method: \'POST\', header: { \'Content-Type\': \'application/json\' }, extraData: JSON.stringify({ title: \'foo\', body: \'bar\' })};httpRequest.request(url, options, (err, data) => { if (!err) { console.log(\"响应状态码:\", data.responseCode); }});
3. PUT请求
import http from \'@ohos.net.http\';async function updateUser(userId: string, userData: object) { let httpRequest = http.createHttp(); try { let response = await httpRequest.request( `https://api.example.com/users/${userId}`, { method: \'PUT\', // 关键设置 header: { \'Content-Type\': \'application/json\' }, extraData: JSON.stringify(userData) // 完整用户数据 } ); console.log(\'更新结果:\', response.result); } finally { httpRequest.destroy(); }}// 调用示例updateUser(\'123\', { name: \'张三\', age: 30 });
4. PATCH 请求
async function updateUserName(userId: string, newName: string) { let httpRequest = http.createHttp(); try { await httpRequest.request( `https://api.example.com/users/${userId}/name`, { method: \'PATCH\', // 关键设置 header: { \'Content-Type\': \'application/json-patch+json\' }, extraData: JSON.stringify([{ \"op\": \"replace\", \"path\": \"/name\", \"value\": newName }]) } ); } finally { httpRequest.destroy(); }}
5. DELETE 请求
async function deletePost(postId: string) { let httpRequest = http.createHttp(); try { let response = await httpRequest.request( `https://api.example.com/posts/${postId}`, { method: \'DELETE\' } // 关键设置 ); if (response.responseCode === 204) { console.log(\'删除成功\'); } } finally { httpRequest.destroy(); }}
三、高级功能实现
1. 文件上传(Multipart)
import fileio from \'@ohos.fileio\';async function uploadFile(filePath: string) { let fileStat = fileio.statSync(filePath); let file = fileio.openSync(filePath, 0o100); // 只读模式 let options = { method: \'POST\', files: [ { filename: \'image.jpg\', name: \'file\', uri: `internal://app/${filePath}`, type: \'image/jpeg\', size: fileStat.size } ] }; httpRequest.upload(url, options, (progress) => { console.log(`上传进度: ${progress.percent}%`); });}
2. 请求拦截器(Axios风格)
// 安装axios:ohpm install @ohos/axiosimport axios from \'@ohos/axios\';// 请求拦截axios.interceptors.request.use(config => { config.header[\'X-Token\'] = getToken(); return config;});// 响应拦截axios.interceptors.response.use( response => { if (response.status !== 200) { throw new Error(\'服务异常\'); } return response.data; }, error => { showToast(\'网络错误\'); return Promise.reject(error); });
四、安全与优化
1. HTTPS证书校验
let sslOptions = { protocols: [http.Protocol.TLSv12], useCipherSuites: [ \'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\' ], ca: \'/path/to/cert.pem\' // 自定义CA证书};httpRequest.request(url, { method: \'GET\', sslOptions});
2. 请求缓存策略
let cacheOptions = { priority: http.HttpCachePriority.LOW, readBehavior: http.HttpCacheReadBehavior.ONLINE};httpRequest.request(url, { method: \'GET\', cacheOptions});
五、实战案例:封装HTTP工具类
export class HttpUtil { private static instance: HttpUtil; private httpRequest: http.HttpRequest; private constructor() { this.httpRequest = http.createHttp(); } static getInstance(): HttpUtil { if (!HttpUtil.instance) { HttpUtil.instance = new HttpUtil(); } return HttpUtil.instance; } async get(url: string, params?: Record) { let query = params ? \'?\' + new URLSearchParams(params).toString() : \'\'; return this.request(\'GET\', url + query); } private async request(method: string, url: string, data?: any) { try { let response = await this.httpRequest.request(url, { method, header: { \'Content-Type\': \'application/json\' }, extraData: data ? JSON.stringify(data) : undefined }); return JSON.parse(response.result); } catch (err) { throw new Error(`HTTP Error: ${err.code}`); } } destroy() { this.httpRequest.destroy(); }}// 使用示例HttpUtil.getInstance().get(\'https://api.example.com/data\', { page: 1 });
六、调试与问题排查
1. 网络状态监听
import network from \'@ohos.net.network\';network.on(\'netAvailable\', (data) => { console.log(`当前网络类型: ${data.netInfo.type}`);});
2. 常见错误码处理
七、性能优化建议
-
连接复用
// 全局保持单例HttpRequestconst httpRequest = http.createHttp();
-
数据压缩
let headers = { \'Accept-Encoding\': \'gzip, deflate\'};
-
分页加载
async function loadPage(page: number) { return httpRequest.get(url, { page, size: 20 });}
总结对比