头图

《HarmonyOSNext 全场景网络通信能力进阶实战:从多网管理到RCP高阶开发》

\##Harmony OS Next ##Ark Ts ##教育

本文适用于教育科普行业进行学习,有错误之处请指出我会修改。

🚀 鸿蒙HTTP请求全指南 | 手把手玩转八大请求方法

🌟 场景速览
支持GET/POST/PUT/DELETE等​​八大请求方法​​,轻松实现数据交互!无论是普通请求还是流式响应,统统搞定~


⚠️ 必看!权限申请

// 在module.json5中添加
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

💡 没有这个权限,你的HTTP请求会直接扑哦!


🔧 接口速查表

接口方法大招效果
createHttp()创建HTTP任务实例
request()发起标准请求
requestInStream()开启流式响应模式
on('headersReceive')订阅响应头事件

📌 普通请求六步走

// 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"
    }]
  }
}

💡 避坑指南

  1. 流式请求必看

    • 收到dataEnd事件前不要关闭连接
    • 大文件传输建议设置readTimeout: 120000(2分钟)
  2. 证书管理雷区

    # Windows用户注意!
    openssl s_client -connect example.com:443 < NUL
  3. 内存优化技巧

    // 及时释放资源
    httpRequest.off('dataReceive'); 
    httpRequest.destroy();

📋 配置参数速查表

参数说明示例值
usingCache启用缓存true
priority请求优先级1-5
clientCert客户端证书{certPath: 'client.pem'}
multiFormDataList多表单数据[{name: 'file', filePath: 'test.txt'}]

🚨 紧急情况处理

遇到证书过期报错?
立即更新APP预置证书,并通过弹窗引导用户升级版本!

// 错误捕获示例
httpRequest.request(url, options, (err) => {
  if (err.code === 2303501) { // 证书错误码
    showDialog("请升级到最新版本");
  }
});

🚀 鸿蒙RCP网络请求终极指南 | 解锁高阶玩法

🌟 RCP vs HTTP 功能大PK

功能亮点HTTP ❌RCP ✅
PATCH请求支持×
自动URL基地址拼接×
请求拦截/取消×
双向证书校验×
流量追踪分析×

🎯 五大核心场景实战

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
  });
});

💡 专家建议

  • 使用session.abort()及时取消长时间未响应请求
  • 通过priority参数设置请求优先级(1-5级)
  • HTTPS请求推荐强制TLS 1.3协议
  • 大文件上传使用TransferRange分片传输

轻松掌握玩转鸿蒙网络通信技巧,!🎯 任何问题欢迎评论区交流~


Turing_010
1 声望0 粉丝