【OpenHarmony-OkHttp移植版】
·
OpenHarmony-OkHttp移植版
为OpenHarmony生态打造的HTTP客户端 - OkHttp移植版(已发布)
让鸿蒙应用的网络通信更加优雅、高效、可靠
项目背景
随着OpenHarmony(鸿蒙)生态系统的快速发展,开发者对高质量网络通信库的需求日益迫切。
当前ohpm平台只有httpclient有okhttp相似的接口功能,但实际能力大相径庭;
OkHttp for OpenHarmony 正是在这样的背景下诞生的。该项目将成熟的OkHttp框架移植到OpenHarmony平台,为鸿蒙应用开发者提供新的解决方案。
核心亮点
🚀 完整的功能支持
- HTTP/HTTPS协议:全面支持HTTP/1.1和TLS协议
- 连接池管理:智能复用TCP连接,大幅提升网络性能
- 磁盘缓存:内置HTTP缓存机制,减少网络请求,节省流量
- 拦截器系统:灵活的责任链模式,轻松实现日志、认证、重试等功能
- WebSocket支持:完整的双向通信能力,满足实时通信需求
- 代理配置:支持HTTP、HTTPS、SOCKS代理,适配各种网络环境
💡 开发者友好的API设计
采用Builder模式构建请求和客户端,API简洁直观:
const client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.cache(cache)
.addInterceptor(loggingInterceptor)
.build();
const request = new Request.Builder()
.url('https://api.example.com/data')
.header('Authorization', 'Bearer token')
.build();
const response = await client.newCall(request).execute();
⚡ 卓越的性能表现
- 连接复用:自动管理连接池,减少TCP握手开销
- GZIP压缩:透明的数据压缩,节省带宽
- 智能缓存:遵循HTTP缓存规范,智能管理缓存策略
技术实现亮点
混合编程架构
项目采用ArkTS + C++混合开发:
- ArkTS层:实现核心HTTP协议栈、连接管理、缓存系统
- C++层:通过NAPI实现IDN(国际化域名)解析,确保全球化支持
完善的模块化设计
library/src/main/ets/
├── OkHttpClient.ts # 客户端核心
├── connection/ # 连接管理模块
├── cache/ # 缓存实现
├── http/ # HTTP协议层
├── ws/ # WebSocket实现
├── tls/ # TLS/SSL配置
错误处理
提供完善的错误类型系统,便于问题定位和处理:
try {
const response = await client.newCall(request).execute();
} catch (error) {
if (error instanceof SocketTimeoutException) {
console.error('请求超时');
} else if (error instanceof UnknownHostException) {
console.error('域名解析失败');
}
}
丰富的应用场景
RESTful API调用
// GET请求
const response = await client.newCall(
new Request.Builder()
.url('https://api.github.com/users/octocat')
.build()
).execute();
// POST JSON
const jsonBody = RequestBody.StringToRequestBody(
JSON.stringify({ name: 'John' }),
MediaType.toMediaType('application/json')
);
await client.newCall(
new Request.Builder()
.url('https://api.example.com/users')
.post(jsonBody)
.build()
).execute();
文件上传
const multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart('file', 'photo.jpg',
RequestBody.create(fileBytes, MediaType.toMediaType('image/jpeg')))
.build();
const response = await client.newCall(
new Request.Builder()
.url('https://api.example.com/upload')
.post(multipartBody)
.build()
).execute();
实时通信(WebSocket)
const webSocket = client.newWebSocket(
new Request.Builder().url('wss://echo.websocket.org').build(),
new WebSocketListener() {
onOpen(ws, response) {
ws.send('Hello Server!');
}
onMessage(ws, text) {
console.log('收到消息:', text);
}
}
);
高级拦截器应用
// 统一Token认证
class AuthInterceptor implements Interceptor {
async intercept(chain: Chain): Promise<Response> {
const token = await getAccessToken();
const request = chain.request().newBuilder()
.header('Authorization', `Bearer ${token}`)
.build();
return await chain.proceed(request);
}
}
// 自动重试机制
class RetryInterceptor implements Interceptor {
async intercept(chain: Chain): Promise<Response> {
let attempt = 0;
while (attempt < 3) {
try {
return await chain.proceed(chain.request());
} catch (error) {
if (++attempt >= 3) throw error;
await sleep(1000 * attempt);
}
}
}
}
快速开始
安装
通过OpenHarmony包管理器安装:
ohpm install @harmony-lib/okhttp
基础使用
import { OkHttpClient, Request } from '@harmony-lib/okhttp';
// 创建客户端
const client = new OkHttpClient.Builder().build();
// 发起请求
const request = new Request.Builder()
.url('https://api.example.com/data')
.build();
// 执行并获取响应
const response = await client.newCall(request).execute();
if (response.isSuccessful) {
const body = await response.body?.toString();
console.log('响应内容:', body);
}
性能优化建议
1. 单例模式使用客户端
// 推荐:全局共享一个客户端实例
export const httpClient = new OkHttpClient.Builder()
.connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
.build();
2. 启用HTTP缓存
const cache = new Cache(
context.cacheDir + '/http-cache',
10 * 1024 * 1024 // 10MB
);
const client = new OkHttpClient.Builder()
.cache(cache)
.build();
3. 合理设置超时时间
const client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
测试与质量保障
项目提供完整的测试服务器(基于Node.js + Express),支持:
- HTTP各种方法测试(GET、POST、PUT、DELETE等)
- HTTPS/TLS连接测试
- 缓存策略验证
- 代理服务器测试
- WebSocket功能测试
- 多文件上传测试
cd testServer
npm install
npm start
开源协议与贡献
本项目采用 Apache License 2.0 开源协议,欢迎社区贡献。
- 仓库地址:https://github.com/SettZhao/okhttp-openHarmony
- 包名:@harmony-lib/okhttp
- 维护者:SettZhao
如何贡献
我们欢迎各种形式的贡献:
- 🐛 提交Bug报告
- 💡 提出新功能建议
- 📝 改进文档
- 🔧 提交代码修复
- ⭐ Star支持项目
未来规划
- HTTP/2 协议支持
- 升级到上游社区最新版本
- 性能benchmark工具
项目信息
- 📦 Package:@harmony-lib/okhttp
- 📄 License:Apache License 2.0
- 🔗 Repository:https://github.com/SettZhao/okhttp-openHarmony
- 📖 Version:1.0.0-rc.0
更多推荐



所有评论(0)