##Harmony OS Next ##Ark Ts ##教育
本文适用于教育科普行业进行学习,有错误之处请指出我会修改。
🚀 鸿蒙 HTTP 请求全指南 | 手把手玩转八大请求方法
🌟 场景速览 支持 GET/POST/PUT/DELETE 等八大请求方法,轻松实现数据交互!无论是普通请求还是流式响应,统统搞定~
⚠️ 必看!权限申请
// 在module.json5中添加
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
}
}
复制代码
💡 没有这个权限,你的 HTTP 请求会直接扑哦!
🔧 接口速查表
📌 普通请求六步走
// 1. 引入模块
import { http } from '@kit.NetworkKit';
// 2. 创建实例
let httpRequest = http.createHttp();
// 3. 订阅响应头事件
httpRequest.on('headersReceive', (header) => {
console.log(`🎯 收到响应头:${JSON.stringify(header)}`);
});
// 4. 发起POST请求
httpRequest.request("https://api.example.com", {
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: JSON.stringify({ key: "value" })
}, (err, data) => {
if (!err) {
// 5. 解析数据
console.log(`📦 响应内容:${data.result}`);
// 6. 销毁实例
httpRequest.destroy();
}
});
复制代码
🌊 流式请求实战
let bufferCache = new ArrayBuffer(0);
// 订阅数据流事件
httpRequest.on('dataReceive', (chunk) => {
// 实时拼接数据块
const newBuffer = new ArrayBuffer(bufferCache.byteLength + chunk.byteLength);
new Uint8Array(newBuffer).set([...new Uint8Array(bufferCache), ...new Uint8Array(chunk)]);
bufferCache = newBuffer;
});
// 监听传输进度
httpRequest.on('dataReceiveProgress', (progress) => {
console.log(`📊 已接收:${progress.receiveSize} / 总计:${progress.totalSize}`);
});
// 发起流式请求
httpRequest.requestInStream("https://bigfile.example.com", {
readTimeout: 120000 // 大文件建议延长超时
}).then((code) => {
console.log(`✅ 状态码:${code}`);
});
复制代码
🔐 证书锁定黑科技
方案一:预置证书文件
// network_config.json配置
{
"domain-config": [{
"domains": [{ "name": "secure.com" }],
"trust-anchors": [{
"certificates": "/data/secure_cert.pem"
}]
}]
}
复制代码
方案二:公钥哈希锁定
# 获取公钥哈希三步曲
openssl x509 -in cert.pem -pubkey -noout > pubkey.pem
openssl asn1parse -in pubkey.pem -out pubkey.der
openssl dgst -sha256 -binary pubkey.der | base64
// 配置示例
{
"pin-set": {
"pin": [{
"digest-algorithm": "sha256",
"digest": "FEDCBA987654321"
}]
}
}
复制代码
💡 避坑指南
流式请求必看
收到dataEnd
事件前不要关闭连接
大文件传输建议设置readTimeout: 120000
(2 分钟)
证书管理雷区
内存优化技巧
📋 配置参数速查表
🚨 紧急情况处理
遇到证书过期报错? 立即更新 APP 预置证书,并通过弹窗引导用户升级版本!
// 错误捕获示例
httpRequest.request(url, options, (err) => {
if (err.code === 2303501) { // 证书错误码
showDialog("请升级到最新版本");
}
});
复制代码
🚀 鸿蒙 RCP 网络请求终极指南 | 解锁高阶玩法
🌟 RCP vs HTTP 功能大 PK
🎯 五大核心场景实战
1️⃣ 基础请求六步曲
// 1️⃣ 创建会话(自带TLS 1.3加密)
const session = rcp.createSession({
security: { tlsVersion: 'TlsV1.3' }
});
// 2️⃣ 构建PATCH请求(局部更新神器)
const req = new rcp.Request(
'https://api.user.com/123',
'PATCH',
{ 'Content-Type': 'application/json' },
{ userName: 'NewName' }
);
// 3️⃣ 发起请求并处理响应
session.fetch(req).then(response => {
console.log('🎉 用户昵称更新成功!');
}).catch(err => {
console.error('💥 更新失败:', err.code);
});
复制代码
2️⃣ 智能 URL 基地址
// 🌐 全局配置API基地址
const session = rcp.createSession({
baseAddress: 'https://api.example.com/v2',
headers: { 'Authorization': 'Bearer xxx' }
});
// 🔄 实际请求自动拼接为 https://api.example.com/v2/users
session.get('/users').then(...);
复制代码
3️⃣ 多表单轰炸式提交
// 📦 构建混合表单数据
const multiForm = new rcp.MultipartForm({
profile: { contentType: 'image/png', contentOrPath: '/selfie.png' },
bio: '全栈开发工程师 | 鸿蒙发烧友'
});
// 🚀 一键提交多类型数据
session.post('/upload', multiForm).then(...);
复制代码
4️⃣ DNS 黑科技配置
// 🔐 安全DNS三件套配置
const dnsConfig = {
dnsRules: [
{ ip: '1.1.1.1' }, // 首选DNS
{ host: 'api.internal', ipAddresses: ['10.0.0.1'] } // 内网解析
],
dnsOverHttps: {
url: 'https://dns.secure.com',
skipCertValidation: true
}
};
// 🌍 创建智能DNS会话
const smartSession = rcp.createSession({ dns: dnsConfig });
复制代码
5️⃣ 全链路监控
// 📊 开启上帝视角监控
const tracingConfig = {
verbose: true,
infoToCollect: {
incomingData: true,
outgoingHeader: true
},
httpEventsHandler: {
onDataReceive: (data) => console.log('📥 收到数据块:', data.length),
onHeaderReceive: (headers) => console.table(headers)
}
};
// 🔍 带监控的会话实例
const tracedSession = rcp.createSession({ tracing: tracingConfig });
复制代码
🔐 安全加固指南
双向证书校验
// 1️⃣ 配置客户端证书
const certConfig = {
clientCert: {
certPath: '/client.pem',
keyPath: '/client.key',
keyPassword: '123456'
}
};
// 2️⃣ 创建安全会话
const secureSession = rcp.createSession({
security: {
tlsOptions: {
caPath: '/ca.pem',
clientCert: certConfig
}
}
});
复制代码
⚡ 性能优化秘籍
拦截器缓存
// 🚄 自定义缓存拦截器
class CacheInterceptor implements rcp.Interceptor {
private cache = new Map();
async intercept(ctx, next) {
const cached = this.cache.get(ctx.url);
if (cached) return cached;
const response = await next(ctx);
this.cache.set(ctx.url, response);
return response;
}
}
// ⚡ 启用缓存加速
const fastSession = rcp.createSession({
interceptors: [new CacheInterceptor()]
});
复制代码
📊 数据分析看板
// 🕒 获取请求时间明细
tracedSession.get('https://analytics.com').then(res => {
console.table({
'DNS查询': res.timeInfo.dnsLookup,
'TCP握手': res.timeInfo.tcpHandshake,
'SSL握手': res.timeInfo.sslHandshake,
'首字节时间': res.timeInfo.ttfb
});
});
复制代码
💡 专家建议
轻松掌握玩转鸿蒙网络通信技巧,!🎯 任何问题欢迎评论区交流~
评论