Cordova Advanced HTTP
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 - read more at LumberBlog.
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-safe-http cordova plugin add cordova-plugin-safe-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 = cordovapluginhttp;
useBasicAuth
This sets up all future requests to use Basic HTTP authentication with the given username and password.
cordovapluginhttp;
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).
cordovapluginhttp;
You can also define headers used for all hosts by using wildcard character "*" or providing only two params.
cordovapluginhttp;cordovapluginhttp;
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/...cordovapluginhttp; // will match http://www.example.com:8080/...cordovapluginhttp;
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.
cordovapluginhttp;
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")
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.
cordovapluginhttp;
getCookieString
Returns saved cookies (as string) matching given URL.
cordovapluginhttp;
setCookie
Add a custom cookie. Takes a URL, a cookie string and an options object. See ToughCookie documentation for allowed options.
cordovapluginhttp;
clearCookies
Clear the cookie store.
cordovapluginhttp;
Asynchronous Functions
These functions all take success and error callbacks as their last 2 arguments.
setSSLCertMode
Set SSL Cert handling mode, being one of the following values:
default
: default SSL cert handling using system's CA certsnocheck
: disable SSL cert checking, trusting all certs (meant to be used only for testing purposes)pinned
: trust only provided certs
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.
⚠️ Your certificate must be DER encoded! If you only have a PEM enoceded certificate see this stackoverflow answer. You want to convert it to a DER encoded certificate with a .cer extension.
// enable SSL pinningcordovapluginhttp; // use system's default CA certscordovapluginhttp; // disable SSL cert checking, only meant for testing purposes, do NOT use in production!cordovapluginhttp;
enableSSLPinning (obsolete)
This function was removed in 2.0.0. Use "setSSLCertMode" to enable SSL pinning (mode "pinned").
acceptAllCerts (obsolete)
This function was removed in 2.0.0. Use "setSSLCertMode" to disable checking certs (mode "nocheck").
disableRedirect
If set to true
, it won't follow redirects automatically. This defaults to false.
cordovapluginhttp;
validateDomainName (obsolete)
This function was removed in v1.6.2. Domain name validation is disabled automatically when you set SSL cert mode to "nocheck".
removeCookies
Remove all cookies associated with a given URL.
cordovapluginhttp;
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.
The options object contains following keys:
method
: HTTP method to be used, defaults toget
, 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 onpost
,put
orpatch
methods)params
: query params to be appended to the URL (only applicable onget
,head
,delete
,upload
ordownload
methods)serializer
: data serializer to be used (only applicable onpost
,put
orpatch
methods), defaults to global serializer value, see setDataSerializer for supported valuestimeout
: timeout value for the request in seconds, defaults to global timeout valueheaders
: headers object (key value pair), will be merged with global valuesfilePath
: filePath to be used during upload and download see uploadFile and downloadFile for detailed informationname
: name 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' ; cordovapluginhttp;
post
Execute a POST request. Takes a URL, data, and headers.
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:
cordovapluginhttp;
failure
The error function receives a response object with 4 properties: status, error, url, and headers (url and headers being optional). status is the HTTP response code as numeric value. error is the error 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: 403 error: 'Permission denied' url: 'http://example.net/noperm' headers: 'content-length': '247'
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.
cordovapluginhttp;
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 a file saved on the device. Takes a URL, parameters, headers, filePath, and the name of the parameter to pass the file along as. See the post documentation for details on what is returned on success and failure.
cordovapluginhttp;
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.
cordovapluginhttp;
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:
- iOS - AFNetworking (MIT licensed)
- Android - http-request (MIT licensed)
- Cookie handling - tough-cookie (BSD-3-Clause licensed)
We made a few modifications to the networking libraries.
Contribute & Develop
We've set up a separate document for our contribution guidelines.