Cordova Advanced HTTP Plugin

raw JSON →
3.3.1 verified Wed Apr 22 auth: no javascript

cordova-plugin-advanced-http is a Cordova/PhoneGap plugin that enables mobile applications to perform HTTP requests using native networking capabilities, offering significant advantages over standard JavaScript requests. Key differentiators include robust SSL/TLS pinning for enhanced security, bypassing browser-imposed CORS restrictions, support for X.509 client certificate-based authentication, and improved handling of HTTP 401 Unauthorized responses. The current stable version is 3.3.1. While there isn't an explicit release cadence, the project is actively maintained with updates detailed in its `CHANGELOG.md`. This plugin is particularly valuable for applications requiring secure communication channels and those needing to circumvent typical webview networking limitations on iOS, Android, and Browser platforms.

error ReferenceError: cordova is not defined
cause Attempted to access `cordova.plugin.http` or other Cordova APIs before the `deviceready` event has fired, meaning the native bridge is not yet initialized.
fix
Ensure all plugin calls are within a document.addEventListener('deviceready', function() { /* plugin code here */ }, false); block.
error Failed to establish TLS connection: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
cause This error typically occurs on Android when SSL pinning is enabled but the provided `.cer` certificates do not match the server's certificate or its trusted chain, or the certificates are not correctly placed/formatted.
fix
Verify that your .cer files are DER-encoded, up-to-date, and correctly placed in platforms/android/app/src/main/assets/certificates (or www/certificates in older setups). Ensure you are pinning against the correct server certificate or a valid intermediate/root CA.
error Native: tried calling HTTP.post, but the HTTP plugin is not installed. Install the HTTP plugin: 'ionic cordova plugin add cordova-plugin-advanced-http'
cause This specific error often arises in Ionic applications when using `@ionic-native/http` wrapper with `cordova-plugin-advanced-http`, where the wrapper might not correctly detect or interface with the underlying native plugin due to namespace differences or incorrect setup.
fix
Double-check that cordova-plugin-advanced-http is installed (ionic cordova plugin add cordova-plugin-advanced-http) and that @ionic-native/http is also installed (npm install @ionic-native/http). Ensure your app.module.ts correctly declares and provides HTTP from @ionic-native/http/ngx. Sometimes, rebuilding the project (ionic cordova platform rm android && ionic cordova platform add android) is necessary.
error Error: A network error occurred.
cause A generic error indicating a problem with the network request itself, which could be due to connectivity issues, incorrect URL, server-side errors, or missing network permissions in `AndroidManifest.xml` (Android) or `Info.plist` (iOS).
fix
Check device network connectivity. Verify the requested URL is correct and accessible. Inspect server logs for errors. Ensure your config.xml and platform-specific manifests have necessary network permissions (e.g., android.permission.INTERNET, android.permission.ACCESS_NETWORK_STATE).
gotcha The plugin is a global object (`cordova.plugin.http`) and is only available after the `deviceready` event fires. Attempting to use it before this event will result in `ReferenceError: cordova is not defined` or `cordova.plugin.http is undefined`.
fix Always wrap calls to `cordova.plugin.http` methods within a `document.addEventListener('deviceready', handler, false)` callback.
breaking Abort functionality for sent requests is not working reliably. Applications relying on the ability to cancel in-flight HTTP requests may experience unexpected behavior or resource leaks.
fix Implement custom timeout mechanisms or design application flow to tolerate unreliable request cancellation. Avoid relying on the plugin's native abort mechanism for critical operations.
gotcha SSL/TLS Pinning requires specific configuration. You must include DER-encoded `.cer` certificates in your app's `www/certificates` folder (or project root for iOS, `platforms/android/assets` for Android). Incorrectly configured certificates or an attempt to pin against a revoked/expired certificate will lead to connection failures.
fix Ensure all `.cer` files are correctly DER-encoded and placed in the specified directories. Thoroughly test pinning against your target server environments (development, staging, production) and manage certificate expiry. Use `setServerTrustMode('nocheck')` *only* for testing, never in production.
gotcha Debugging network requests made through this plugin can be challenging as they are handled natively and do not appear in the browser's developer tools (e.g., Safari's network tab for iOS). This makes inspecting request/response headers and bodies difficult.
fix Utilize comprehensive server-side logging or integrate dedicated mobile debugging proxies (e.g., Charles Proxy, Fiddler) to inspect native HTTP traffic. For debugging within the app, add extensive `console.log` statements around API calls.
gotcha The `setDataSerializer` method's `urlencoded` option does not support serializing deep (nested) JavaScript objects, whereas `json` does. Using `urlencoded` with complex data structures will lead to incorrect payload formatting.
fix For nested data, always use `setDataSerializer('json')`. If `urlencoded` is required, flatten your data object or manually serialize complex parts before passing them to the plugin.
deprecated The `AndroidBlacklistSecureSocketProtocols` preference allows disabling insecure SSL/TLS protocols, which is critical for security. However, its effectiveness depends on correctly identifying and blacklisting outdated protocols (e.g., `SSLv3`, `TLSv1`). Failure to update this list as new vulnerabilities emerge can leave the application exposed.
fix Regularly review and update the `AndroidBlacklistSecureSocketProtocols` preference in `config.xml` with current recommendations for secure protocols. Consult Android's SSLSocket documentation for valid protocol names and industry best practices for TLS configuration.
npm install cordova-plugin-advanced-http
yarn add cordova-plugin-advanced-http
pnpm add cordova-plugin-advanced-http

This quickstart demonstrates how to initialize and use `cordova-plugin-advanced-http` after the `deviceready` event, including setting global headers, configuring data serializers, and making basic GET and POST requests.

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
  console.log('Cordova is ready. Initializing Advanced HTTP plugin.');

  const http = cordova.plugin.http;
  const API_BASE_URL = 'https://jsonplaceholder.typicode.com';

  // Set a global header for all requests
  http.setHeader('*', 'X-Custom-Header', 'MyValue');
  console.log('Set global custom header.');

  // Set data serializer to JSON for POST/PUT requests
  http.setDataSerializer('json');
  console.log('Set data serializer to JSON.');

  // Perform a GET request
  http.get(
    `${API_BASE_URL}/posts/1`,
    { /* parameters */ },
    { /* headers */ },
    (response) => {
      console.log('GET Success:', response.status, JSON.parse(response.data));
    },
    (response) => {
      console.error('GET Error:', response.status, response.error);
    }
  );

  // Perform a POST request
  const postData = { title: 'foo', body: 'bar', userId: 1 };
  http.post(
    `${API_BASE_URL}/posts`,
    postData,
    { 'Content-Type': 'application/json' }, // Can override global serializer's content type
    (response) => {
      console.log('POST Success:', response.status, JSON.parse(response.data));
    },
    (response) => {
      console.error('POST Error:', response.status, response.error);
    }
  );

  // Example of using SSL pinning (requires .cer files in www/certificates)
  // Uncomment and configure if you have .cer files
  /*
  http.setServerTrustMode('pinned', () => {
    console.log('SSL pinning enabled.');
  }, (error) => {
    console.error('Failed to enable SSL pinning:', error);
  });
  */
}