npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@cordova-ohos/cordova-plugin-advanced-http

v3.3.2

Published

Cordova Advanced Http Plugin

Readme

cordova-plugin-advanced-http

zh-CN en

本项目基于 [email protected] 开发,本文档重点阐述其在 OpenHarmony(OHOS)系统中的具体应用。

简介

cordova-plugin-advanced-http 是 Harmony Cordova 生态系统中一款高级 HTTP 网络请求插件,在原生 XMLHttpRequest 基础上进行功能增强与性能优化。支持 SSL 证书 pinning、请求/响应拦截、文件上传下载、cookie 管理等核心能力,解决传统网络请求在安全性、稳定性和功能扩展性上的痛点,适用于对网络请求有高阶需求的企业级应用开发,兼容 Android、iOS、Browser 及 OHOS 平台,本文档主要说明在 OHOS 系统中的应用。

  • 安全增强:支持 SSL 证书 pinning 防止中间人攻击,可配置信任自定义 CA 证书

  • 功能全面:覆盖 GET/POST/PUT/DELETE 等请求方法,支持表单提交、JSON 数据、文件上传下载

  • 拦截可控:提供请求/响应拦截器,可统一处理请求头、参数加密、响应解密等逻辑

  • Cookie 管理:支持手动设置、获取、清除 Cookie,适配需要登录状态保持的场景

  • 离线支持:可配置请求超时重试、网络状态检测,提升弱网环境下的请求稳定性

  • 跨平台兼容:统一 Android、iOS、Browser 平台 API 调用方式,减少平台适配成本

该插件广泛应用于金融、电商、医疗等对网络安全和稳定性要求较高的领域,经过大量生产环境验证,性能与可靠性均处于行业领先水平。

支持平台

  • Android:API 19 及以上(Android 4.4+)

  • iOS:10.0 及以上

  • OHOS:5.0+

  • Browser:主流现代浏览器(Chrome、Firefox、Safari 等)

下载安装

通过 hcordova CLI 即可快速安装插件,支持从 npm 仓库、GitCode 仓库安装,也可指定版本安装,仅需针对 OHOS 平台安装时添加对应参数。

从 npm 安装(推荐)

使用 hcordova 命令化工具安装,支持全平台或仅 OHOS 平台安装:

# 安装 hcordova 命令化工具
npm install -g hcordova

# 全平台安装插件(最新稳定版)
hcordova plugin add cordova-plugin-advanced-http

# 仅安装到 OHOS 平台
hcordova plugin add cordova-plugin-advanced-http --platform ohos

# 安装指定版本(仅 OHOS 平台)
hcordova plugin add [email protected] --platform ohos

从 GitCode 仓库安装

如需测试最新开发功能,可从 GitCode 仓库安装(仅 OHOS 平台):

# 仅安装到 OHOS 平台
hcordova plugin add https://gitcode.com/CPF-Cordova/cordova-plugin-advanced-http.git --platform ohos

# 指定标签/分支安装
hcordova plugin add https://gitcode.com/CPF-Cordova/cordova-plugin-advanced-http.git@develop --platform ohos

离线安装(本地包)

适用于无网络环境,先下载插件包到本地,再执行离线安装:

# 下载插件包到本地(示例路径:~/Downloads/cordova-plugin-advanced-http)
# 执行离线安装
hcordova plugin add ~/Downloads/cordova-plugin-advanced-http --platform ohos

安装后验证

安装完成后,可通过以下命令验证插件是否成功添加到项目中:

# 查看已安装的插件列表,若包含本插件 ID 则表示插件已成功安装
hcordova plugin list

卸载

# Cordova CLI 全平台卸载
hcordova plugin remove cordova-plugin-advanced-http 

# 指定 OHOS 平台卸载
hcordova plugin remove cordova-plugin-advanced-http --platform ohos

约束与限制

  • SSL 认证:OHOS 平台下,插件使用 openssl 进行 SSL 校验,不依赖系统 CA 证书,需手动配置 CA 根证书(存放于 rawfile/certificates 目录,.cer 结尾)。

  • 双向认证:使用双向认证时,需使用 openssl 3.0 以上版本制作 p12 证书,避免因加密算法过时导致的报错。

  • 文件路径:文件上传下载需使用原生路径,可通过 cordova.file 相关 API 获取合法路径。

兼容性

支持:

| 项目 | 版本/信息 | |-----|--------| | SDK | API12+ | | IDE | DevEco Studio: 5.0+ | | ROM | 5.1+ | | Emulator | OpenHarmony 6.0+ |

在以下版本中已测试通过:

| 项目 | 版本/信息 | |-----|--------| | @cordova-ohos/ohos | 14.0.1-ohos-14.0.1 | | SDK | 5.0.0(12) | | IDE | DevEco Studio: 6.0.13.200 | | ROM | 5.1.0.120 SP3 | | Emulator | OpenHarmony 6.0.1(21) |

权限要求

需授予应用网络访问权限(用于与远程服务器通信)、文件读写权限(用于文件上传下载),插件自动适配各平台基础权限,无需额外手动配置。

使用示例

示例 1:基础 GET/POST 请求

实现简单的 GET 请求获取数据、POST 请求提交数据功能。

// GET 请求
function sendHttpGet() {
    cordova.plugin.http.get('http://www.tongecn.com/update/server.xml', {
        id: '12',
        message: 'test'
    }, { Authorization: 'OAuth2: token' }, function(response) {
        document.getElementById("getInfo").innerHTML = response.status;
        console.log('成功:', response.data);
    }, function(response) {
        document.getElementById("getInfo").innerHTML = response.error;
        console.log('错误:', response.status, response.error);
    });
}

// POST 请求
function sendHttpPost() {
    cordova.plugin.http.setHeader('ceshi.tongecn.com', 'Header', 'Value');
    cordova.plugin.http.setCookie('https://ceshi.tongecn.com', "auth=12345;SameSite=none");
    const options = {
        method: 'POST',
        data: {
            bookname: "《cordova编程》",
            author: "马弓手"
        },
        serializer:"json"
    };

    cordova.plugin.http.sendRequest('https://ceshi.tongecn.com/member/test.jsp', options, function(response) {
        document.getElementById("postInfo").innerHTML = response.status;
    }, function(response) {
        document.getElementById("postInfo").innerHTML = response.error;
    });
}

示例 2:文件上传与下载

实现文件下载、上传及取消操作,适配 OHOS 平台文件路径规范。

// 下载文件
function downloadHttpFile() {
    var uri = "https://cordova.apache.org/static/img/cordova_bot.png";
    window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
        document.getElementById("downloadInfo").innerHTML = "正在下载...";
        var targetPath = dirEntry.toURL() + "cordova_bot.png";
        cordova.plugin.http.downloadFile(
            uri,
            { id: '12', message: 'test' },
            { Authorization: 'OAuth2: token' },
            targetPath,
            function(entry, response) {
                document.getElementById("downloadInfo").innerHTML = entry.name;
                console.log(entry.fullPath);
            },
            function(response) {
                document.getElementById("downloadInfo").innerHTML = response.error;
            }
        );
    });
}

// 上传文件
function uploadHttpFile() {
    window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
        var targetPath = dirEntry.toURL() + "cordova_bot.png";
        const filePath = [targetPath, dirEntry.toURL() + "cordova_bot.png"];
        const name = ['picture', 'document'];

        cordova.plugin.http.uploadFile("https://ceshi.tongecn.com/servlet/ImageTempUpload", {
            id: '12',
            message: 'test'
        }, { Authorization: 'OAuth2: token' }, filePath, name, function (response) {
            document.getElementById("uploadInfo").innerHTML = response.status;
        }, function (response) {
            document.getElementById("uploadInfo").innerHTML = response.error;
        });
    });
}

// 取消上传
function cancelUploadHttpFile() {
    window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
        var targetPath = dirEntry.toURL() + "cordova_bot.png";
        const filePath = [targetPath];
        const name = ['picture'];

        var reqId = cordova.plugin.http.uploadFile("https://ceshi.tongecn.com/servlet/ImageTempUpload", {
            id: '12',
            message: 'test'
        }, { Authorization: 'OAuth2: token' }, filePath, name, function (response) {
            console.log(response.status);
        }, function (response) {
            console.log(response.error);
        });

        // 取消上传
        cordova.plugin.http.abort(reqId, function(result) {
            document.getElementById("cancelUploadInfo").innerHTML = result.aborted;
        }, function(response) {
            document.getElementById("cancelUploadInfo").innerHTML = response.error;
        });
    });
}

示例 3:SSL 认证配置

实现单向认证和双向认证配置,保障请求安全。

// 单向认证(SSL 证书锁定)
function setServerTrustMode() {
    cordova.plugin.http.setServerTrustMode('pinned', function() {
        document.getElementById("serverTrustInfo").innerHTML = "设置成功";
    }, function(errorInfo) {
        document.getElementById("serverTrustInfo").innerHTML = errorInfo;
    });
}

// 双向认证
function setClientTrustMode() {
    // 将 base64 格式的 p12 证书转换为 ArrayBuffer
    function base64ToArrayBuffer(base64) {
        const binaryString = atob(base64);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        return bytes.buffer;
    }

    var p12base64 = "MIIRvwIBAzCCEXUGCSqGSIb3DQEHAaC.....="; // 完整 base64 格式 p12 证书
    const myPkcs12ArrayBuffer = base64ToArrayBuffer(p12base64);
    cordova.plugin.http.setClientAuthMode('buffer', {
        rawPkcs: myPkcs12ArrayBuffer,
        pkcsPassword: 'your_cert_password'
    }, function(){
        document.getElementById("clientTrustInfo").innerHTML = "设置成功";
    }, function(errorInfo){
        document.getElementById("clientTrustInfo").innerHTML = "设置失败";
    });
}

使用说明

核心 API

1. 请求 API 说明

支持多种 HTTP 请求方法,统一接收 URL、参数/数据、请求头、成功回调、失败回调五个参数,其中 sendRequest 方法支持更灵活的配置。

/*
* url (String): 请求 URL
* params/data (Object): 请求参数或数据(params 适用于 GET/HEAD 等,data 适用于 POST/PUT 等)
* headers (Object): 请求头对象
* success (Function): 成功回调函数,接收响应对象
* error (Function): 失败回调函数,接收错误响应对象
*/

// GET 请求
cordova.plugin.http.get(url, params, headers, success, error);

// POST 请求
cordova.plugin.http.post(url, data, headers, success, error);

// PUT 请求
cordova.plugin.http.put(url, data, headers, success, error);

// DELETE 请求
cordova.plugin.http.delete(url, params, headers, success, error);

// PATCH 请求
cordova.plugin.http.patch(url, data, headers, success, error);

// HEAD 请求
cordova.plugin.http.head(url, params, headers, success, error);

// 通用请求方法(支持更多配置)
cordova.plugin.http.sendRequest(url, options, success, error);
success 回调响应对象
{
  status: 200, // HTTP 响应码(数值型)
  data: '{"id": 12, "message": "test"}', // 服务器响应数据(字符串)
  url: 'http://example.net/rest', // 最终请求 URL(含重定向后)
  headers: { // 响应头(键值对,全小写)
    'content-length': '247'
  }
}
error 回调响应对象
{
  status: 403, // HTTP 响应码或内部错误码(正值为 HTTP 码,负值为内部错误)
  error: 'Permission denied', // 错误信息(字符串)
  url: 'http://example.net/noperm', // 最终请求 URL(可选)
  headers: { // 响应头(可选)
    'content-length': '247'
  }
}
sendRequest options 配置

options 对象用于配置请求相关参数,支持以下键值:

  • method:HTTP 请求方法(默认 get),可选值:get、post、put、patch、head、delete、options、upload、download

  • data:请求负载数据(适用于 post、put、patch 方法)

  • params:URL 查询参数(适用于 get、head、delete、upload、download 方法)

  • serializer:数据序列化器(适用于 post、put、patch 方法),可选值:json、urlencoded、utf8、multipart、raw

  • responseType:预期响应类型(默认 text),可选值:text、json、arraybuffer、blob

  • timeout:请求超时时间(单位:秒,默认使用全局超时)

  • followRedirect:是否自动跟随重定向(默认 true)

  • headers:请求头对象(与全局请求头合并)

  • filePath:文件上传/下载的文件路径(适用于 upload、download 方法)

  • name:文件上传时的文件名称(可指定多个,适用于多文件上传)

2. 文件 API

上传文件(支持多文件上传)
// 单个文件上传
const filePath = '/data/storage/el2/base/somepicture.jpg'; // 原生路径
const name = 'picture';

// 多个文件上传
const filePath = ['/data/storage/el2/base/somepicture.jpg', '/data/storage/el2/base/somedocument.doc'];
const name = ['picture', 'document'];

cordova.plugin.http.uploadFile(url, params, headers, filePath, name, success, error);
下载文件
const targetPath = '/data/storage/el2/base/somepicture.jpg'; // 下载后保存的原生路径
cordova.plugin.http.downloadFile(url, params, headers, targetPath, success, error);
取消上传/下载
// requestId 是 uploadFile/downloadFile 方法返回的 ID
cordova.plugin.http.abort(requestId, success, error);

3. 配置方法 API

// 设置数据序列化器(全局)
cordova.plugin.http.setDataSerializer('json'); // 可选:json、urlencoded、utf8、multipart、raw

// 设置请求超时时间(单位:秒)
cordova.plugin.http.setRequestTimeout(30);

// 设置全局请求头
cordova.plugin.http.setHeader('*', 'Authorization', 'Bearer token123'); // 所有域名
cordova.plugin.http.setHeader('*.example.com', 'X-Custom-Header', 'value'); // 指定域名

// 设置是否自动跟随重定向(全局)
cordova.plugin.http.setFollowRedirect(true);

4. Cookie 管理 API

// 设置 Cookie
cordova.plugin.http.setCookie('https://example.com', 'token=abc123');

// 获取指定 URL 的 Cookie
cordova.plugin.http.getCookies('https://example.com', success, error);

// 清除所有 Cookie
cordova.plugin.http.clearCookies();

5. 安全配置 API

单向认证(客户端验证服务端)
/*
* SSL 模式选项:
* 'default': 不验证服务端 SSL 证书(Android 默认使用系统 CA 证书,OHOS 不使用系统 CA 证书)
* 'pinned': 校验服务端 SSL 证书(需提供 CA 根证书,存放于 rawfile/certificates 目录,.cer 结尾)
* 'nocheck': 不验证服务端 SSL 证书
* 'legacy': 与 pinned 一致
*/
cordova.plugin.http.setServerTrustMode('pinned', success, error);
双向认证(客户端与服务端互相验证)
/*
* 模式选项:
* 'buffer': 使用 p12 格式证书(需传入 ArrayBuffer 类型证书数据和密码)
* 'systemstore': 与 none 一致,不开启双向认证
* 'none': 不开启双向认证
*/
cordova.plugin.http.setClientAuthMode('buffer', {
    rawPkcs: myPkcs12ArrayBuffer, // p12 证书的 ArrayBuffer 格式
    pkcsPassword: 'your_cert_password' // 证书密码
}, success, error);

6. 数据序列化说明

插件支持 5 种数据序列化格式,可通过 setDataSerializer 方法全局设置,也可在 sendRequest 的 options 中单独配置:

  • json:默认格式,Content-Type 为 application/json,数据为对象或数组

  • urlencoded:Content-Type 为 application/x-www-form-urlencoded,数据为键值对对象

  • utf8:Content-Type 为 text/plain,数据为字符串

  • multipart:Content-Type 为 multipart/form-data,数据为 FormData 对象

  • raw:Content-Type 为 application/octet-stream,数据为 ArrayBuffer 或 Uint8Array

核心配置

可在项目 config.xml 中预设全局配置,如最低 TLS 版本:

<!-- 在 config.xml 添加支持的最低 TLS 版本号 -->
<preference name="MinTLSSecureSocketProtocols" value="TLSv12" />
<!-- 版本从低到高:SSLv3,TLSv10,TLSv11,TLSv12,TLSv13,默认建议使用 TLSv12 -->

新增特性

这里结合插件 API 对 SSL/TLS 网络通讯简要说明一下

  • (1)使用函数 setServerTrustMode 设置客户端验证服务端模式,服务端在 SSL/TLS 捂手阶段,服务端发送证书到客户端,客户端通过本地根证书对服务端提供的证书进行校验,以确认服务端身份,也就是单向认证,即客户端验证服务端身份,服务端不验证客户端身份,浏览器上网通常采用此机制,使用浏览器上网,根证书库维护有操作系统维护或者浏览器本身维护,根证书有 CA 提供,不能使用自签名证书,但是使用此插件和服务器通讯,可以使用自签名证书,根证书有自己的 APP 维护,同样可以实现加密通讯。

    • nocheck:不验证服务端 SSL 证书

    • default:不验证服务端 SSL 证书,Android 默认使用系统提供的 CA 证书,OHOS 插件不使用系统 CA 证书

    • pinned:校验服务端的 SSL 证书,需提供 CA 根证书,CA 根证书可以在申请证书的服务商直接下载,下载后存在在 rawfile/certificates 目录下,必须 .cer 结尾

    • legacy:和 pinned 一致。

      说明:客户端验证服务端,cordova-ohos 提供了两种方式,第一个是不校验,第二个是有 APP 提供 CA 根证书,不使用系统提供的 CA 证书,主要原因在于 cordova 内部使用 openssl 校验,因 openssl 对 CA 证书的存放要求所致,也为提高校验效率,因此 cordova-ohos 使用 APP 提供的 CA 根证书校验。根证书在服务商申请证书时可直接下载 CA 根证书,CA 的根证书是全网公开的。

  • (2)使用函数 setClientAuthMode 设置服务端验证客户端模式,服务端在 SSL/TLS 捂手阶段,服务端会要求客户端发送客户端证书,客户端提供证书后,服务端通过服务端预存的根证书对客户端证书进行校验,以确认客户端的身份,也就是双向认证,即客户端验证服务端,服务端也验证客户端,服务端验证客户端,可以使用自签名证书,因为根证书的维护在服务端。使用双向认证,不仅要配置客户端证书,也需要服务端配置和支持,大部分金融级安全多采用此模式。

    • buffer:使用给定的 p12 格式的证书,一般情况下,可以直接下载 pfx 就是 p12 证书的二进制格式,但是直接下载 pfx 证书,一般采用是已经废弃的加密算法加密的,不能正确提取证书和 key,所以可以自行制作 p12 证书,使用 openssl 3.0 以上版本制作 p12 证书参考如下:

      # fullchain.crt 包含证书链和根证书,证书链在上,根证书在下。
      openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt -chain -CAfile fullchain.crt -password pass:yourpassword
      # 该命令不检验证书链,可不包含根证书,p12 证书建议包含根证书
      openssl pkcs12 -export -out server.p12 -inkey server.key -in server.crt  -certfile chain.crt -password pass:yourpassword
    • none:不提供证书,不开启不开启双向认证

    • systemstore:和 none 保持一致,不开启双向认证

    • 说明:

      • 1,默认不开启双向认证
      • 2,设置双向认证时报错:error:0308010C:digital envelope routines::unsupported,是因为使用了传统的老的加密算法合并 p12 文件,如果使用 openssl 将密码、证书和证书链合并为 p12,请使用 openssl 3.0 以上版本。直接下载的 pfx 格式的证书一般会这个错误。
  • (3) 此插件上传和下载文件不支持进度通知,如果要显示进度通知的,请使用 cordova-plugin-file-transfer 插件,参考原文档即可,这里不再详细说明

  • (4) 在 config.xml 文件中配置支持的最低 TLS 协议版本,不再支持 TLS 的黑名单配置 AndroidBlacklistSecureSocketProtocols 参数

目录结构

cordova-plugin-advanced-http/
├── src/                          # 源代码目录
│   └── main/                     # 主要源代码
│       └── cpp/                  # C++ 原生代码
│           └── Http/             # HTTP 请求模块
│               ├── CordovaHttpPlugin.cpp  # HTTP 插件 C++ 实现
│               └── CordovaHttpPlugin.h    # HTTP 插件头文件
├── www/                          # Web 资源目录
│   ├── advanced-http.js          # 高级 HTTP 请求主入口文件
│   ├── cookie-handler.js         # Cookie 处理模块
│   ├── dependency-validator.js   # 依赖验证模块
│   ├── error-codes.js            # 错误码定义
│   ├── global-configs.js         # 全局配置管理
│   ├── helpers.js                # 辅助函数工具集
│   ├── js-util.js                # JavaScript 工具函数
│   ├── local-storage-store.js    # 本地存储管理
│   ├── lodash.js                 # Lodash 工具库(或子集)
│   ├── messages.js               # 消息提示定义
│   ├── ponyfills.js              # Polyfill 填充库
│   ├── public-interface.js       # 公共接口暴露
│   ├── umd-tough-cookie.js       # Tough-Cookie 的 UMD 打包版本
│   ├── url-util.js               # URL 工具函数
│   └── LICENSE                   # Web 资源的许可证文件
├── LICENSE                       # 项目开源许可证
├── OAT.xml                       # 华为 OpenHarmony 审核配置
├── package.json                  # Node.js 包配置
├── plugin.xml                    # Cordova 插件描述文件
└── README.md                     # 项目说明文档

贡献代码

使用过程中发现任何问题都可以提 Issue ,当然也非常欢迎发 PR 共建。

许可证

本插件基于 Apache License 2.0 开源,详见 LICENSE 文件。

官方资源