Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

cordova-plugin-ebw-advanced-http

HeB-Mobile1MIT2.2.1

Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning

cordova, device, ecosystem:cordova, cordova-ios, cordova-android, ssl, tls

readme

Cordova Advanced HTTP

npm version downloads/month MIT Licence Build Status

Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS, Android and Browser.

This is a fork of Wymsee's Cordova-HTTP plugin.

Advantages over Javascript requests

  • Background threading - all requests are done in a background thread.
  • Handling of HTTP code 401 - read more at Issue CB-2415.
  • SSL Pinning

Updates

Please check CHANGELOG.md for details about updating to a new version.

Installation

The plugin conforms to the Cordova plugin specification, it can be installed using the Cordova / Phonegap command line interface.

phonegap plugin add cordova-plugin-advanced-http

cordova plugin add cordova-plugin-advanced-http

Usage

Plain Cordova

This plugin registers a global object located at cordova.plugin.http.

With Ionic-native wrapper

Check the Ionic docs for how to use this plugin with Ionic-native.

Synchronous Functions

getBasicAuthHeader

This returns an object representing a basic HTTP Authorization header of the form {'Authorization': 'Basic base64encodedusernameandpassword'}

var header = cordova.plugin.http.getBasicAuthHeader('user', 'password');

useBasicAuth

This sets up all future requests to use Basic HTTP authentication with the given username and password.

cordova.plugin.http.useBasicAuth('user', 'password');

setHeader

Set a header for all future requests to a specified host. Takes a hostname, a header and a value (must be a string value).

cordova.plugin.http.setHeader('Hostname', 'Header', 'Value');

You can also define headers used for all hosts by using wildcard character "*" or providing only two params.

cordova.plugin.http.setHeader('*', 'Header', 'Value');
cordova.plugin.http.setHeader('Header', 'Value');

The hostname also includes the port number. If you define a header for www.example.com it will not match following URL http://www.example.com:8080.

// will match http://www.example.com/...
cordova.plugin.http.setHeader('www.example.com', 'Header', 'Value');

// will match http://www.example.com:8080/...
cordova.plugin.http.setHeader('www.example.com:8080', 'Header', 'Value');

setDataSerializer

Set the data serializer which will be used for all future PATCH, POST and PUT requests. Takes a string representing the name of the serializer.

cordova.plugin.http.setDataSerializer('urlencoded');

You can choose one of these:

  • urlencoded: send data as url encoded content in body (content type "application/x-www-form-urlencoded")
  • json: send data as JSON encoded content in body (content type "application/json")
  • utf8: send data as plain UTF8 encoded string in body (content type "plain/text")

This defaults to urlencoded. You can also override the default content type headers by specifying your own headers (see setHeader).

Caution: urlencoded does not support serializing deep structures whereas json does.

setRequestTimeout

Set how long to wait for a request to respond, in seconds.

cordova.plugin.http.setRequestTimeout(5.0);

setFollowRedirect

Configure if it should follow redirects automatically. This defaults to true.

cordova.plugin.http.setFollowRedirect(true);

getCookieString

Returns saved cookies (as string) matching given URL.

cordova.plugin.http.getCookieString(url);

setCookie

Add a custom cookie. Takes a URL, a cookie string and an options object. See ToughCookie documentation for allowed options.

cordova.plugin.http.setCookie(url, cookie, options);

clearCookies

Clear the cookie store.

cordova.plugin.http.clearCookies();

Asynchronous Functions

These functions all take success and error callbacks as their last 2 arguments.

setServerTrustMode

Set server trust mode, being one of the following values:

  • default: default SSL trustship and hostname verification handling using system's CA certs
  • legacy: use legacy default behavior (< 2.0.3), excluding user installed CA certs (only for Android)
  • nocheck: disable SSL certificate checking and hostname verification, trusting all certs (meant to be used only for testing purposes)
  • pinned: trust only provided certificates

To use SSL pinning you must include at least one .cer SSL certificate in your app project. You can pin to your server certificate or to one of the issuing CA certificates. Include your certificate in the www/certificates folder. All .cer files found there will be loaded automatically.

:warning: Your certificate must be DER encoded! If you only have a PEM encoded certificate read this stackoverflow answer. You want to convert it to a DER encoded certificate with a .cer extension.

// enable SSL pinning
cordova.plugin.http.setServerTrustMode('pinned', function() {
  console.log('success!');
}, function() {
  console.log('error :(');
});

// use system's default CA certs
cordova.plugin.http.setServerTrustMode('default', function() {
  console.log('success!');
}, function() {
  console.log('error :(');
});

// disable SSL cert checking, only meant for testing purposes, do NOT use in production!
cordova.plugin.http.setServerTrustMode('nocheck', function() {
  console.log('success!');
}, function() {
  console.log('error :(');
});

disableRedirect (deprecated)

This function was deprecated in 2.0.9. Use "setFollowRedirect" instead.

setSSLCertMode (deprecated)

This function was deprecated in 2.0.8. Use "setServerTrustMode" instead.

enableSSLPinning (obsolete)

This function was removed in 2.0.0. Use "setServerTrustMode" to enable SSL pinning (mode "pinned").

acceptAllCerts (obsolete)

This function was removed in 2.0.0. Use "setServerTrustMode" to disable checking certs (mode "nocheck").

validateDomainName (obsolete)

This function was removed in v1.6.2. Domain name validation is disabled automatically when you set server trust mode to "nocheck".

removeCookies

Remove all cookies associated with a given URL.

cordova.plugin.http.removeCookies(url, callback);

sendRequest

Execute a HTTP request. Takes a URL and an options object. This is the internally used implementation of the following shorthand functions (post, get, put, patch, delete, head, uploadFile and downloadFile). You can use this function, if you want to override global settings for each single request. Check the documentation of the respective shorthand function for details on what is returned on success and failure.

:warning: You need to encode the base URL yourself if it contains special characters like whitespaces. You can use encodeURI() for this purpose.

The options object contains following keys:

  • method: HTTP method to be used, defaults to get, needs to be one of the following values:
    • get, post, put, patch, head, delete, upload, download
  • data: payload to be send to the server (only applicable on post, put or patch methods)
  • params: query params to be appended to the URL (only applicable on get, head, delete, upload or download methods)
  • serializer: data serializer to be used (only applicable on post, put or patch methods), defaults to global serializer value, see setDataSerializer for supported values
  • responseType: expected response type, defaults to text, needs to be one of the following values:
    • text: data is returned as decoded string, use this for all kinds of string responses (e.g. XML, HTML, plain text, etc.)
    • json data is treated as JSON and returned as parsed object
    • arraybuffer: data is returned as ArrayBuffer instance
    • blob: data is returned as Blob instance
  • timeout: timeout value for the request in seconds, defaults to global timeout value
  • followRedirect: enable or disable automatically following redirects
  • headers: headers object (key value pair), will be merged with global values
  • filePath: file path(s) to be used during upload and download see uploadFile and downloadFile for detailed information
  • name: name(s) to be used during upload see uploadFile for detailed information

Here's a quick example:

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

post

Execute a POST request. Takes a URL, data, and headers.

cordova.plugin.http.post('https://google.com/', {
  test: 'testString'
}, {
  Authorization: 'OAuth2: token'
}, function(response) {
  console.log(response.status);
}, function(response) {
  console.error(response.error);
});

success

The success function receives a response object with 4 properties: status, data, url, and headers. status is the HTTP response code as numeric value. data is the response from the server as a string. url is the final URL obtained after any redirects as a string. headers is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

Here's a quick example:

{
  status: 200,
  data: '{"id": 12, "message": "test"}',
  url: 'http://example.net/rest'
  headers: {
    'content-length': '247'
  }
}

Most apis will return JSON meaning you'll want to parse the data like in the example below:

cordova.plugin.http.post('https://google.com/', {
  id: 12,
  message: 'test'
}, { Authorization: 'OAuth2: token' }, function(response) {
  // prints 200
  console.log(response.status);
  try {
    response.data = JSON.parse(response.data);
    // prints test
    console.log(response.data.message);
  } catch(e) {
    console.error('JSON parsing error');
  }
}, function(response) {
  // prints 403
  console.log(response.status);

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

failure

The error function receives a response object with 4 properties: status, error, url, and headers (url and headers being optional). status is a HTTP response code or an internal error code. Positive values are HTTP status codes whereas negative values do represent internal error codes. error is the error response from the server as a string or an internal error message. url is the final URL obtained after any redirects as a string. headers is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.

Here's a quick example:

{
  status: 403,
  error: 'Permission denied',
  url: 'http://example.net/noperm'
  headers: {
    'content-length': '247'
  }
}

:warning: An enumeration style object is exposed as cordova.plugin.http.ErrorCode. You can use it to check against internal error codes.

get

Execute a GET request. Takes a URL, parameters, and headers. See the post documentation for details on what is returned on success and failure.

cordova.plugin.http.get('https://google.com/', {
  id: '12',
  message: 'test'
}, { Authorization: 'OAuth2: token' }, function(response) {
  console.log(response.status);
}, function(response) {
  console.error(response.error);
});

put

Execute a PUT request. Takes a URL, data, and headers. See the post documentation for details on what is returned on success and failure.

patch

Execute a PATCH request. Takes a URL, data, and headers. See the post documentation for details on what is returned on success and failure.

delete

Execute a DELETE request. Takes a URL, parameters, and headers. See the post documentation for details on what is returned on success and failure.

head

Execute a HEAD request. Takes a URL, parameters, and headers. See the post documentation for details on what is returned on success and failure.

uploadFile

Uploads one or more file(s) saved on the device. Takes a URL, parameters, headers, filePath(s), and the name(s) of the parameter to pass the file along as. See the post documentation for details on what is returned on success and failure.

// e.g. for single file
const filePath = 'file:///somepicture.jpg';
const name = 'picture';

// e.g. for multiple files
const filePath = ['file:///somepicture.jpg', 'file:///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);
});

downloadFile

Downloads a file and saves it to the device. Takes a URL, parameters, headers, and a filePath. See post documentation for details on what is returned on failure. On success this function returns a cordova FileEntry object.

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

  // prints the filePath
  console.log(entry.fullPath);
}, function(response) {
  console.error(response.error);
});

Browser support

This plugin supports a very restricted set of functions on the browser platform. It's meant for testing purposes, not for production grade usage.

Following features are not supported:

  • Manipulating Cookies
  • Uploading and Downloading files
  • Pinning SSL certificate
  • Disabling SSL certificate check
  • Disabling transparently following redirects (HTTP codes 3xx)

Libraries

This plugin utilizes some awesome open source libraries:

We made a few modifications to the networking libraries.

Contribute & Develop

We've set up a separate document for our contribution guidelines.

changelog

Changelog

2.2.0

  • Feature #239: add enumeration style object for error codes
  • Feature #253: add support for response type "json"
  • Feature #127: add multiple file upload (thanks SDA SE Open Industry Solutions and nilswitschel)

2.1.1

  • Fixed #224: response type "arraybuffer" and "blob" not working on browser platform

2.1.0

  • Feature #216: Support for response type arraybuffer
  • Feature #171: Support for response type blob
  • Feature #205: Add preference for configuring OKHTTP version (thanks RougeCiel)

2.0.11

  • Fixed #221: headers not set on Android when request fails due to non-success status code

2.0.10

  • Fixed #218: headers are used as params on browser platform

2.0.9

  • Fixed #204: broken support for cordova-android < 7.0

  • :warning: Deprecation: Deprecated "disableRedirect" in favor of "setFollowRedirect"

2.0.8

  • Fixed #198: cookie header is always passed even if there is no cookie
  • Fixed #201: browser implementation is broken due to broken dependency
  • Fixed #197: iOS crashes when multiple request are done simultaneously (reverted a8e3637)
  • Fixed #189: error code mappings are not precise
  • Fixed #200: compatibility with Java 6 is broken due to string switch on Android

  • :warning: Deprecation: Deprecated "setSSLCertMode" in favor of "setServerTrustMode"

2.0.7

  • Fixed #195: URLs are double-encoded on Android

2.0.6

  • Fixed #187: setSSLCertMode with "default" throws an error on Android
  • Fixed #115: HTTP connections are not kept alive on iOS (thanks MorpheusDe97)

2.0.5

  • Fixed #185: need more detailed SSL error message

2.0.4

  • Fixed #179: sending empty string with utf8 serializer throws an exception

2.0.3

  • Fixed #172: plugin does not respect user installed CA certs on Android

Important information

We've changed a default behavior on Android. User installed CA certs are respected now. If you don't want this for your needs, you can switch back to old behavior by setting SSL cert mode to legacy.

2.0.2

  • Fixed #142: Plugin affected by REDoS Issue of tough-cookie
  • Fixed #157: Arguments are double URL-encoded on "downloadFile" (thanks TheZopo)
  • Fixed #164: Arguments are double URL-encoded on "head" (thanks ath0mas)

2.0.1

  • Fixed #136: Content-Type header non-overwritable on browser platform

2.0.0

  • Feature #103: implement HTTP SSL cert modes

  • :warning: Breaking Change: Removed AngularJS (v1) integration service

  • :warning: Breaking Change: Removed "enableSSLPinning" and "acceptAllCerts", use "setSSLCertMode" instead
  • :warning: Breaking Change: Certificates must be placed in "www/certificates" folder

1.11.1

  • Fixed #92: headers not deserialized on platform "browser"

1.11.0

  • Feature #77: allow overriding global settings for each single request
  • Feature #11: add support for "browser" platform

1.10.2

  • Fixed #78: overriding header "Content-Type" not working on Android
  • Fixed #79: PATCH operation not working on Android API level 19 and older (thanks chax)
  • Fixed #83: App crashes on error during download operation on iOS (thanks troyanskiy)
  • Fixed #76: upload sequence is not respecting order of operations needed by some sites (thanks Johny101)

  • :warning: Deprecation: AngularJS service is deprecated now and will be removed anytime soon

1.10.1

  • Fixed #71: does not encode query string in URL correctly on Android
  • Fixed #72: app crashes if response encoding is not UTF-8 (thanks jkfb)

1.10.0

  • Feature #34: add new serializer "utf8" sending utf-8 encoded plain text (thanks robertocapuano)

1.9.1

  • Fixed #45: does not encode arrays correctly as HTTP GET parameter on Android
  • Fixed #54: requests are not responding on iOS with non-string values in header object
  • Fixed #58: white-list of allowed content-types should be removed for iOS

v1.9.0

  • Feature #44: "getCookieString" method is exposed
  • Feature #43: added support for content type "application/javascript" on iOS (thanks wh33ler)
  • Feature #46: "setCookie" allows adding custom cookies

v1.8.1

  • Fixed #27: "uploadFile" method doesn't return data object on iOS (thanks Faisalali23 and laiyinjie)
  • Fixed #40: generic error codes are different on Android and iOS

v1.8.0

  • Feature #33: response object contains response url

v1.7.1

  • Fixed #36: setting basic authentication not working correctly (thanks jkfb)
  • Fixed #35: Android headers are not normalized (not returned in lowercase)
  • Fixed #26: JSON request with array data is not working on Android (JSON error)

v1.7.0

  • Feature #24: "setHeader" allows configuring headers for specified host

v1.6.2

  • Change #29: removed "validateDomainName" (see info notice)
  • Fixed #31: request fails throwing error on erroneous cookies
  • Fixed #28: added support for content type "application/hal+json" on iOS (thanks ryandegruyter)

Important information

We've decided to remove the validateDomainName() method, because people were complaining that acceptAllCerts(true) is not behaving as expected. And also it's not a good idea to disable domain name validation while using valid certs, because it pretends having a secure connection, but it isn't.

You should either use valid certs with domain name validation enabled (safe for production use) or accept any certs without domain name validation (only for private dev environments). I strongly discourage using fake certs in public networks.

Therefore we are disabling domain name validation automatically, when you set acceptAllCerts(true). So if you were using validateDomainName() function, you need to remove this function call for v1.6.2+.

v1.6.1

  • Fixed #23: PATCH method broken on android

v1.6.0

  • Feature #18: implemented PATCH method (thanks akhatri for android implementation)
  • Feature #21: added redirection control (thanks to notsyncing and kesozjura)
  • Fixed #16: cordova tries to run build script during plugin install

v1.5.10

  • Fixed #10: fix gzip decompression when request header accepts gzip compression (thanks to DayBr3ak)
  • Fixed #13: fix angular integration for setDataSerializer (thanks to RangerRick)
  • Added some missing documentation (thanks to RangerRick)

v1.5.9

  • Fixed case-sensitive folder name of Android source files

v1.5.8

  • Use the same error codes if a request timed out

v1.5.7

  • Fixed a bug in cookie handling (cookies containing an "Expires" string)
  • Added setRequestTimeout function to set the timeout in seconds for all further requests

v1.5.6

  • All response header keys are converted to lowercase (iOS only)

v1.5.5

  • added a function to remove all cookies for a URL

v1.5.4

  • fixed an error if the response has no "headers" field

v1.5.3

  • handles cookies correctly on non-success response from server
  • throws error when a callback function is missing

v1.5.2

  • fixed missing file "umd-tough-cookie.js“ (caused by missing file ".npmignore")

v1.5.1

  • fixed case-sensitive path name of android source files ("CordovaHTTP" --> "cordovahttp")

v1.5.0

  • added cookie handling
  • cookies are persisted via web storage API

v1.4.0

Previous changelog (cordova-plugin-http)

v1.2.0

  • Added support for TLSv1.1 and TLSv1.2 for android versions 4.1-4.4 (API levels 16-19)

Potentially Breaking Changes that really shouldn't matter because you shouldn't be using SSLv3

  • Dropped SSLv3 support for all API Levels < 20. It will now only work on API Levels 20-22.

v1.1.0

  • Fixed the body of errors not being returned in iOS
  • Updated AFNetworking to 3.1.0

Potentially Breaking Changes

  • Disable encoding get() URLS in android (Thanks to devgeeks)

v1.0.3

  • Fixed version number in plugin.xml

v1.0.2

  • Fixed bug using useBasicAuth and setHeader from angular

v1.0.1

  • updated README

v1.0.0

  • Added getBasicAuthHeader function
  • Added necessary iOS framework (Thanks to EddyVerbruggen)
  • Request internet permission in android (Thanks to mbektchiev)
  • Fix acceptAllCerts doesn't call callbacks (Thanks to EddyVerbruggen)
  • Add validateDomainName (Thanks to denisbabineau)
  • Add HEAD request support (untested) (Thanks to denisbabineau)

Potentially Breaking Changes

  • Update cordova file plugin dependency (Thanks to denisbabineau)
  • useBasicAuthHeader and setHeader are now synchronous functions
  • updated AFNetworking to 3.0.4 - only iOS 7+ is now supported
  • updated http-request to 6.0

v0.1.4

  • Support for certificates in www/certificates folder (Thanks to EddyVerbruggen)

v0.1.3

  • Update AFNetworking to 2.4.1 for iOS bug fix in Xcode 6

v0.1.2

  • Fixed plugin.xml for case sensitive filesystems (Thanks to andrey-tsaplin)

v0.1.1

  • Fixed a bug that prevented building

v0.1.0

  • Initial release

Contributions not noted above

  • Fixed examples (Thanks to devgeeks)
  • Reports SSL Handshake errors rather than giving a generic error (Thanks to devgeeks)
  • Exporting http as a module (Thanks to pvsaikrishna)
  • Added Limitations section to readme (Thanks to cvillerm)
  • Fixed examples (Thanks to hideov)