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.1

Published

Cordova Advanced Http Plugin

Downloads

150

Readme

cordova-plugin-advanced-http

npm version

cordova-plugin-advanced-http 是一款为 Cordova 应用打造的高级 HTTP 网络请求插件,在原生 XMLHttpRequest 基础上进行功能增强与性能优化。支持 SSL 证书 pinning、请求 / 响应拦截、文件上传下载、cookie 管理等核心能力,解决传统网络请求在安全性、稳定性和功能扩展性上的痛点,适用于对网络请求有高阶需求的企业级应用开发。

1. 插件概述

作为 Cordova 生态中功能全面的网络请求插件,cordova-plugin-advanced-http 基于原生平台网络框架(鸿蒙基于openssl)开发,具备以下核心优势:

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

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

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

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

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

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

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

2. 安装方式

2.1 基础安装(推荐)

在 Cordova 项目根目录执行以下命令,插件会自动处理依赖与基础配置:

# 安装hcordova
npm install -g hcordova

# 安装最新版本
hcordova plugin add cordova-plugin-advanced-http

# 安装指定版本
hcordova plugin add [email protected] --platform ohos

3.2 从 GitCode 源码安装

若需使用开发中的最新功能,可直接从 GitCode 仓库安装:

hcordova plugin add https://gitcode.com/OpenHarmony-Cordova/cordova-plugin-advanced-http.git --platform ohos

3.3 卸载插件

如需移除插件,执行以下命令即可清理相关配置与依赖:

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

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

4. 快速开始

// GET请求
cordova.plugin.http.get('https://api.example.com/data', 
  {}, // 参数
  {}, // 请求头
  function(response) {
    console.log('成功:', response.data);
  },
  function(response) {
    console.log('错误:', response.status, response.error);
  }
);

// POST请求
cordova.plugin.http.post('https://api.example.com/api',
  { key: 'value' }, // 请求体
  { 'Content-Type': 'application/json' }, // 请求头
  function(response) {
    console.log('成功:', response.data);
  },
  function(response) {
    console.log('错误:', response.status, response.error);
  }
);

5. API说明

5.1 请求API说明

参数说明:
/*
* url (String): 请求URL
* params/data (Object): 请求参数或数据
* 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 success函数接收一个具有4个属性的响应对象:状态、数据、url和标头。status是作为数值的HTTP响应代码。data是来自服务器的字符串形式的响应。url是任何重定向后获得的最终url。headers是一个包含headers的对象。返回对象的键是标头名称,值是相应的标头值。所有标题名称都是小写的。
//成功后返回
{
  status: 200,
  data: '{"id": 12, "message": "test"}',
  url: 'http://example.net/rest'
  headers: {
    'content-length': '247'
  }
}
  • error error函数接收一个具有4个属性的响应对象:状态、错误、url和标头(url和标头是可选的)。状态是HTTP响应代码或内部错误代码。正值是HTTP状态代码,而负值确实表示内部错误代码。error是服务器以字符串或内部错误消息的形式发出的错误响应。url是任何重定向后以字符串形式获得的最终url。headers是一个包含headers的对象。返回对象的键是标头名称,值是相应的标头值。所有标题名称都是小写的。

    {
      status: 403,
      error: 'Permission denied',
      url: 'http://example.net/noperm'
      headers: {
        'content-length': '247'
      }
    }
  • sendRequest options 选项对象包含的键信息说明

选项对象(options)用于配置请求相关参数,其包含的键(keys)及具体说明如下:

  • method:要使用的HTTP方法 默认值:get

    • 可选值范围:getpostputpatchheaddeleteoptionsuploaddownload
  • data:要发送到服务器的负载数据 适用场景:仅适用于postputpatch方法

  • params:要附加到URL后的查询参数 适用场景:仅适用于getheaddeleteuploaddownload方法

  • serializer:要使用的数据序列化器 适用场景:仅适用于postputpatch方法,默认值:全局序列化器值, 支持值说明:参考setDataSerializer获取支持的序列化器值

  • responseType:预期的响应类型,默认值:text,可选值及说明:

    • text:数据以解码后的字符串形式返回,适用于所有字符串类型响应(如XML、HTML、纯文本等)
    • json:数据被视为JSON并以解析后的对象形式返回,当响应体为空时返回undefined
    • arraybuffer:数据以ArrayBuffer实例形式返回,当响应体为空时返回null
    • blob:数据以Blob实例形式返回,当响应体为空时返回null
  • timeout:请求的超时时间(单位:秒) 默认值:全局超时时间值

  • followRedirect:是否启用自动跟随重定向 说明:布尔值,用于控制请求过程中是否自动处理重定向响应

  • headers:请求头对象(键值对形式) 说明:将与全局请求头值合并后作为最终请求头

  • filePath:上传和下载过程中要使用的文件路径 详细说明:参考uploadFiledownloadFile获取具体信息

  • name:上传过程中要使用的名称(可指定多个) 详细说明:参考uploadFile获取具体信息

const options = {
  method: 'post',
  data: { id: 12, message: 'test' },
  headers: { Authorization: 'OAuth2: token' }
};

cordova.plugin.http.sendRequest('https://google.com/', options, function(response) {
  // prints 200
  console.log(response.status);
}, function(response) {
  // prints 403
  console.log(response.status);

  //prints Permission denied
  console.log(response.error);
});

5.2 文件API

5.2.1 上传文件(支持同时上传多个文件)

//单个文件上传
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("https://google.com/", {
    id: '12',
    message: 'test'
}, { Authorization: 'OAuth2: token' }, filePath, name, function(response) {
    console.log(response.status);
}, function(response) {
    console.error(response.error);
});

5.2.2 文件下载

cordova.plugin.http.downloadFile(
  "https://google.com/",
  { id: '12', message: 'test' },
  { Authorization: 'OAuth2: token' },
  '/data/storage/el2/base/somepicture.jpg',
  // success callback
  function(entry, response) {
    // prints the filename
    console.log(entry.name);

    // prints the filePath
    console.log(entry.fullPath);

    // prints all header key/value pairs
    Object.keys(response.headers).forEach(function (key) {
      console.log(key, response.headers[key]);
    });
  },
  // error callback
  function(response) {
    console.error(response.error);
  }
);

5.2.3 取消上传/下载

//requestId事情downloadFile/uploadFile返回的ID
cordova.plugin.http.abort(requestId, function(result) {
  console.log(result.aborted);
}, function(response) {
  console.error(response.error);
});

5.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');

//设置是否自动跟随重定向。默认值为true
cordova.plugin.http.setFollowRedirect(true);

5.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.5 安全配置 API

5.5.1 单向认证设置

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

/*
* SSL模式选项:
* 'default':不验证服务端SSL证书,安卓默认使用系统提供的CA证书,鸿蒙的这个插件不使用系统CA证书
* 'pinned': 校验服务端的SSL证书,需提供CA根证书,CA根证书可以在申请证书的服务商直接下载,下载后存在在rawfile/certificates目录下,必须.cer结尾
* 'nocheck': 不验证服务端SSL证书
* 'legacy':和pinned一致。
*/

// SSL证书锁定
cordova.plugin.http.setServerTrustMode('pinned', success, error);

//
cordova.plugin.http.setServerTrustMode('nocheck', success, error);

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

5.5.2 双向认证设置

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

/*
* buffer:使用给定的p12格式的证书,一般情况下,我们可以直接下载pfx就是p12证书的二进制格式,但是直接下载pfx证书,一般采用是已经废弃的加密算法加密的,不能正确提取证书和key,所以我们可以自行制作p12证书。见说明。
* systemstore:和none保持一致,不开启双向认证
*/
//开启双向认证
cordova.plugin.http.setClientAuthMode('buffer', {
    rawPkcs: myPkcs12ArrayBuffer,
    pkcsPassword: 'abc830806'
}, success, error);

//不开启双向认证
cordova.plugin.http.setClientAuthMode('systemstore', {}, success, fail);
//不开启双向认证
cordova.plugin.http.setClientAuthMode('none', {}, success, fail);

说明:

  • 1,默认不开启双向认证

  • 2,设置双向认证时报错:error:0308010C:digital envelope routines::unsupported,是因为使用了传统的老的加密算法合并p12文件,如果使用openssl将密码、证书和证书链合并为p12,请使用openssl3.0以上版本。直接下载的pfx格式的证书一般会这个错误。

  • 3,使用openssl3.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

5.6 数据序列化

//插件支持5种数据序列化格式:

// 1. JSON格式(默认)
cordova.plugin.http.setDataSerializer('json');
// Content-Type: application/json
// 数据格式: 对象或数组

// 2. URL编码格式
cordova.plugin.http.setDataSerializer('urlencoded');
// Content-Type: application/x-www-form-urlencoded
// 数据格式: 键值对对象

// 3. UTF8纯文本
cordova.plugin.http.setDataSerializer('utf8');
// Content-Type: text/plain
// 数据格式: 字符串

// 4. 多部分表单
cordova.plugin.http.setDataSerializer('multipart');
// Content-Type: multipart/form-data
// 数据格式: FormData对象

// 5. 原始二进制
cordova.plugin.http.setDataSerializer('raw');
// Content-Type: application/octet-stream
// 数据格式: ArrayBuffer 或 Uint8Array

6. 核心配置

插件安装后支持通过代码动态配置核心参数,也可在 config.xml 中预设全局配置,满足不同场景需求。

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

7. 使用示例

//发送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"
    };

    var requestId = cordova.plugin.http.sendRequest('https://ceshi.tongecn.com/member/test.jsp', options, function(response) {
        // prints 200
        console.log(response.status);
        document.getElementById("postInfo").innerHTML = response.status;
    }, function(response) {
        // prints 403
        console.log(response.status);
        //prints Permission denied
        console.log(response.error);
    });
}

//发送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.status);
    }, function(response) {
        console.error(response.error);
    });
}

//下载文件
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,
            // success callback
            function(entry, response) {
                // prints the filename
                console.log(entry.name);
                document.getElementById("downloadInfo").innerHTML = entry.name;
                // prints the filePath
                console.log(entry.fullPath);
                // prints all header key/value pairs
                Object.keys(response.headers).forEach(function (key) {
                    console.log(key, response.headers[key]);
                });
            },
            // error callback
            function(response) {
                console.error(response.error);
            }
        );
    });
}

//上传文件
function uploadHttpFile() {
    window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
        var targetPath = dirEntry.toURL() + "cordova_bot.png";
        // e.g. for single file
        //const filePath = targetPath;
        //const name = 'cordova_bot.png';

        // e.g. for multiple files 上传了两个文件
        const filePath = [dirEntry.toURL() + "cordova_bot.png", 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) {
            console.log(response.status);
            document.getElementById("uploadInfo").innerHTML = response.status;
        }, function (response) {
            console.error(response.error);
        });
    });
}

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

        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.error(response.status);
        });

        cordova.plugin.http.abort(reqId, function(result) {
            // prints if request was aborted: true | false
            console.log(result.aborted);
            document.getElementById("cancelUploadInfo").innerHTML = result.aborted;
        }, function(response) {
            console.error(response.error);
        });
    });
}

//下载文件并取消
function cancelDownloadHttpFile() {
    cordova.plugin.http.setRequestTimeout(6.0);
    cordova.plugin.http.setReadTimeout(5.0);

    var uri = "https://cordova.apache.org/static/img/cordova_bot.png";
    window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
        var targetPath = dirEntry.toURL() + "cordova_bot.png";
        var reqId = cordova.plugin.http.downloadFile(
            uri,
            { id: '12', message: 'test' },
            { Authorization: 'OAuth2: token' },
            targetPath,
            // success callback
            function(entry, response) {
                console.log(response.status);
            },
            // error callback
            function(response) {
                console.error(response.status);
            }
        );
        cordova.plugin.http.abort(reqId, function(result) {
            // prints if request was aborted: true | false
            console.log(result.aborted);
            document.getElementById("cancelDownloadInfo").innerHTML = result.aborted;
        }, function(response) {
            console.error(response.error);
        });

    });
}

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

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

//设置双向认证
function setClientTrustMode() {
    var p12base64 = "MIIRvwIBAzCCEXUGCSqGSIb3DQEHAaC.....="; //省略了
    const myPkcs12ArrayBuffer = base64ToArrayBuffer(p12base64);
    cordova.plugin.http.setClientAuthMode('buffer', {
        rawPkcs: myPkcs12ArrayBuffer,
        pkcsPassword: 'abc830806'
    }, function(){
        document.getElementById("clientTrustInfo").innerHTML = "设置成功";
    }, function(errorInfo){
        document.getElementById("clientTrustInfo").innerHTML = "设置失败";
    });

}

参考资源