Coder Social home page Coder Social logo

silkimen / cordova-plugin-advanced-http Goto Github PK

View Code? Open in Web Editor NEW
392.0 12.0 314.0 2.04 MB

Cordova / Phonegap plugin for communicating with HTTP servers. Allows for SSL pinning!

License: MIT License

Java 14.85% Objective-C 37.27% JavaScript 47.19% Shell 0.46% CSS 0.09% HTML 0.14%

cordova-plugin-advanced-http's Introduction

Cordova Advanced HTTP

npm version MIT Licence downloads/month

Travis Build Status GitHub 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

  • SSL / TLS Pinning
  • CORS restrictions do not apply
  • X.509 client certificate based authentication
  • Handling of HTTP code 401 - read more at Issue CB-2415

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

Plugin Preferences

AndroidBlacklistSecureSocketProtocols: define a blacklist of secure socket protocols for Android. This preference allows you to disable protocols which are considered unsafe. You need to provide a comma-separated list of protocols (check Android SSLSocket#protocols docu for protocol names).

e.g. blacklist SSLv3 and TLSv1:

<preference name="AndroidBlacklistSecureSocketProtocols" value="SSLv3,TLSv1" />

Currently known issues

  • aborting sent requests is not working reliably

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 or null).

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
    • default content type "application/x-www-form-urlencoded"
    • data must be an dictionary style Object
  • json: send data as JSON encoded content in body
    • default content type "application/json"
    • data must be an Array or an dictionary style Object
  • utf8: send data as plain UTF8 encoded string in body
    • default content type "plain/text"
    • data must be a String
  • multipart: send FormData objects as multipart content in body
    • default content type "multipart/form-data"
    • data must be an FormData instance
  • raw: send data as is, without any processing
    • default content type "application/octet-stream"
    • data must be an Uint8Array or an ArrayBuffer

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

⚠️ urlencoded does not support serializing deep structures whereas json does.

⚠️ multipart depends on several Web API standards which need to be supported in your web view. Check out https://github.com/silkimen/cordova-plugin-advanced-http/wiki/Web-APIs-required-for-Multipart-requests for more info.

setRequestTimeout

Set how long to wait for a request to respond, in seconds. For Android, this will set both connectTimeout and readTimeout. For iOS, this will set timeout interval. For browser platform, this will set timeout.

cordova.plugin.http.setRequestTimeout(5.0);

setConnectTimeout (Android Only)

Set connect timeout for Android

cordova.plugin.http.setRequestTimeout(5.0);

setReadTimeout (Android Only)

Set read timeout for Android

cordova.plugin.http.setReadTimeout(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. Cookie will persist until removed with removeCookies or clearCookies.

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.

⚠️ 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 :(');
});

setClientAuthMode

Configure X.509 client certificate authentication. Takes mode and options. mode being one of following values:

  • none: disable client certificate authentication
  • systemstore (only on Android): use client certificate installed in the Android system store; user will be presented with a list of all installed certificates
  • buffer: use given client certificate; you will need to provide an options object:
    • rawPkcs: ArrayBuffer containing raw PKCS12 container with client certificate and private key
    • pkcsPassword: password of the PKCS container
  // enable client auth using PKCS12 container given in ArrayBuffer `myPkcs12ArrayBuffer`
  cordova.plugin.http.setClientAuthMode('buffer', {
    rawPkcs: myPkcs12ArrayBuffer,
    pkcsPassword: 'mySecretPassword'
  }, success, fail);

  // enable client auth using certificate in system store (only on Android)
  cordova.plugin.http.setClientAuthMode('systemstore', {}, success, fail);

  // disable client auth
  cordova.plugin.http.setClientAuthMode('none', {}, success, fail);

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.

⚠️ 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, options, 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, returns undefined when response body is empty
    • arraybuffer: data is returned as ArrayBuffer instance, returns null when response body is empty
    • blob: data is returned as Blob instance, returns null when response body is empty
  • 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'
  }
}

⚠️ 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.

options

Execute a OPTIONS 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 as first and the response object as second parameter.

cordova.plugin.http.downloadFile(
  "https://google.com/",
  { id: '12', message: 'test' },
  { Authorization: 'OAuth2: token' },
  'file:///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);
  }
);

abort

Abort a HTTP request. Takes the requestId which is returned by sendRequest and its shorthand functions (post, get, put, patch, delete, head, uploadFile and downloadFile).

If the request already has finished, the request will finish normally and the abort call result will be { aborted: false }.

If the request is still in progress, the request's failure callback will be invoked with response { status: -8 }, and the abort call result { aborted: true }.

⚠️ Not supported for Android < 6 (API level < 23). For Android 5.1 and below, calling abort(reqestId) will have no effect, i.e. the requests will finish as if the request was not cancelled.

// start a request and get its requestId
var requestId = cordova.plugin.http.downloadFile("https://google.com/", {
  id: '12',
  message: 'test'
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry, response) {
  // prints the filename
  console.log(entry.name);

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

  // prints the status code
  console.log(response.status);
}, function(response) {
  // if request was actually aborted, failure callback with status -8 will be invoked
  if(response.status === -8){
    console.log('download aborted');
  } else {
    console.error(response.error);
  }
});

//...

// abort request
cordova.plugin.http.abort(requestId, function(result) {
  // prints if request was aborted: true | false
  console.log(result.aborted);
}, 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)
  • Circumventing CORS restrictions

Libraries

This plugin utilizes some awesome open source libraries:

We made a few modifications to the networking libraries.

CI Builds & E2E Testing

This plugin uses amazing cloud services to maintain quality. CI Builds and E2E testing are powered by:

Local Testing

First, install current package with npm install to fetch dev dependencies.

Then, to execute Javascript tests:

npm run test:js

And, to execute E2E tests:

  • setup local Android sdk and emulators, or Xcode and simulators for iOS
    • launch emulator or simulator
  • install Appium (see Getting Started)
    • start appium
  • run
    • updating client and server certificates, building test app, and running e2e tests
npm run test:android
npm run test:ios

Contribute & Develop

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

cordova-plugin-advanced-http's People

Contributors

0verrfl0w avatar akhatri avatar alexander-gruenewald avatar allie-wake-up avatar andrey-tsaplin avatar antikalk avatar ath0mas avatar chax avatar chrisjdev avatar ciknowles avatar csullivan102 avatar daybr3ak avatar denisbabineau avatar dependabot[bot] avatar devgeeks avatar dmcnamara avatar eddyverbruggen avatar h4ck-root avatar hideov avatar ikosta avatar johny101 avatar pvsaikrishna avatar robertocapuano avatar russaa avatar ryandegruyter avatar silkimen avatar wh33ler avatar youyue123 avatar yushrajewon avatar zfir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-advanced-http's Issues

HTTP load failed

HTTP is failing to load and I cant use it. I am getting this error everytime http is called.

2017-09-27 21:39:18.361086-0400 TekIT[7181:4408659] TIC TCP Conn Failed [17:0x1c4169480]: 1:61 Err(61)
2017-09-27 21:39:18.361252-0400 TekIT[7181:4408659] Task <102BC563-64BD-4762-905C-A7242C48722E>.<1> HTTP load failed (error code: -1004 [1:61])
2017-09-27 21:39:18.418646-0400 TekIT[7181:4408747] Task <102BC563-64BD-4762-905C-A7242C48722E>.<1> finished with error - code: -1004
2017-09-27 21:39:25.281009-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 13, 1024 bytes): [57] Socket is not connected
2017-09-27 21:39:25.284177-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 20, 1024 bytes): [57] Socket is not connected
2017-09-27 21:39:25.285926-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 23, 1024 bytes): [57] Socket is not connected
2017-09-27 21:39:25.286046-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 7, 1024 bytes): [57] Socket is not connected
2017-09-27 21:39:25.294724-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 16, 1024 bytes): [57] Socket is not connected
2017-09-27 21:39:25.295923-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 24, 1024 bytes): [57] Socket is not connected
2017-09-27 21:39:25.295988-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 26, 1024 bytes): [57] Socket is not connected
2017-09-27 21:39:25.299818-0400 TekIT[7181:4408747] [] nw_socket_get_input_frames recvmsg(fd 27, 1024 bytes): [57] Socket is not connected

Here is my ionic info:

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.12.0
    ionic (Ionic CLI) : 3.12.0

global packages:

    cordova (Cordova CLI) : 7.0.1 

local packages:

    @ionic/app-scripts : 2.1.3
    Cordova Platforms  : ios 4.4.0
    Ionic Framework    : ionic-angular 3.6.0

System:

    ios-deploy : 1.9.2 
    Node       : v6.11.2
    npm        : 3.10.10 
    OS         : macOS Sierra
    Xcode      : Xcode 9.0 Build version 9A235 

Misc:

    backend : legacy

Not sure whats going on

Failed with Adobe PhoneGap Build

When compiling project with Adobe PhoneGap Build service - https://build.phonegap.com/ - it fails.

/project/src/com/synconset/cordovahttp/CordovaHttpDownload.java:18: error: package org.apache.cordova.file does not exist
import org.apache.cordova.file.FileUtils;
^
/project/src/com/synconset/cordovahttp/CordovaHttpDownload.java:49: error: cannot find symbol
JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file);
^
symbol: variable FileUtils
location: class CordovaHttpDownload
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
2 errors
:compileDebugJavaWithJavac FAILED

FAILURE: Build failed with an exception.

There's a mention of cordova-plugin-file in the log also:

Fetching plugin "cordova-plugin-advanced-http@^1.8.1" via npm
Installing "cordova-plugin-advanced-http" at "1.8.1" for android
Fetching plugin "cordova-plugin-file@>=2.0.0" via npm
Installing "cordova-plugin-file" at "5.0.0" for android
Plugin doesn't support this project's cordova-android version. cordova-android: 6.1.2, failed version requirement: >=6.3.0
Skipping 'cordova-plugin-file' for android

JSON request with array data is not working on Android (JSON error)

Hello, I am getting JSON error when I would like to send array data in post request

        this.http.setDataSerializer("json");
        this.http
            .post(
            "https://localhost/api/create",
            [{ test: 1 }, { test: 2 }],
            {
                "Accept": "application/json",
                "Content-Type": "application/json"
            }
            )
            .then((response) => {
                console.log('response', response);
            })
            .catch((error) => {
                console.log('error', error);
            })
        ;

I try somethink like below but still same error JSON error

this.http.setDataSerializer("urlencoded");

        this.http
            .post(
            "https://localhost/api/create",
            JSON.stringify([{ test: 1 }, { test: 2 }]),
            {
                "Accept": "application/json",
                "Content-Type": "application/json"
            }
            )
            .then((response) => {
                console.log('response', response);
            })
            .catch((error) => {
                console.log('error', error);
            })
            ;

Plagin
cordova-plugin-advanced-http 1.5.10 "Advanced HTTP plugin"

How can I send json request with array data?

Thanks!

NSException SSL pinning

Hello.
I have problems with ios.
I have the latest version of the plugin - 1.7.1.
When checking the certificate for ios error: "libc++abi.dylib: terminating with uncaught exception of type NSException"
But the Android works well.
Could you help me, please?

Session cookies

Hello. I would like to ask how handle session cookies. Cookies are not send to server.
Cookie header of reaponse is 'set-cookie': [ 'JSESSIONID=dhs-srcyD+z-w6mjCNKS8lRH; Path=/api; Secure' ],

Log of request:
first request

[HPM] GET /api/user/getCurrentUserInfo -> https://test.org
Request { _headers:
   { 'accept-encoding': 'gzip',
     connection: 'close',
     host: 'test.org',
     'user-agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.2; HTC One mini Build/KOT49H)',
     cookie: '',
     authorization: 'Basic ZmFpdE0OkZhaXQxMjM0ISE=',
     accept: 'application/json',
     'accept-charset': 'UTF-8' } }
	 
Response {
  headers:
   { date: 'Thu, 28 Sep 2017 14:08:47 GMT',
     server: 'Apache',
     pragma: 'No-cache',
     'cache-control': 'no-cache',
     expires: 'Thu, 01 Jan 1970 01:00:00 CET',
     'set-cookie': [ 'JSESSIONID=dhs-srcyD+z-w6mjCNKS8lRH; Path=/api; Secure' ],
     connection: 'close',
     'transfer-encoding': 'chunked',
     'content-type': 'application/json' },
  statusCode: 200,
  statusMessage: 'OK'
}

next request without JSESSIONID cookie

[HPM] POST /api/portfolio/getPortfolioOverview -> https://test.org
Request { _headers:
   { 'content-length': '66',
     'accept-encoding': 'gzip',
     connection: 'close',
     host: 'test.org',
     'user-agent': 'Dalvik/1.6.0 (Linux; U; Android 4.4.2; HTC One mini Build/KOT49H)',
     'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
     cookie: '',
     authorization: 'Basic ZmFpdE0OkZhaXQxMjM0ISE=',
     accept: 'application/json',
     'accept-charset': 'UTF-8' }
}

Response {
  headers:
   { date: 'Thu, 28 Sep 2017 14:08:47 GMT',
     server: 'Apache',
     'set-cookie': [ 'JSESSIONID=aZnfv5xMRpG9qfjHrocnHxBi; Path=/api; Secure' ],
     connection: 'close',
     'transfer-encoding': 'chunked',
     'content-type': 'application/json' },
  method: null,
  statusCode: 500,
  statusMessage: 'Internal Server Error' 
}

Cordova plugins

cordova plugin ls
cordova-plugin-advanced-http 1.5.10 "Advanced HTTP plugin"
cordova-plugin-compat 1.0.0 "Compat"
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-crosswalk-webview 2.2.0 "Crosswalk WebView Engine"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-file 4.3.3 "File"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.1 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
ionic-plugin-keyboard 2.2.1 "Keyboard"

Can you help we what I am doing wrong. Thanks you

Get response URL

I have a specific scenario where the API I'm calling redirects me to a different success/failure URL (both with status 200 😭).

It doesn't look like the HTTPResponse object contains the URL.

I'm wondering if it's possible to get this added to the library?

Enabling TLS in iframe

This plugin works great to enable TLS for post and get functions for Android 4.1+. My issue now is that I need to enable TLS for iframes as well. Can I use this plugin to somehow do that?

An error occurred while running cordova plugin add cordova-plugin-advanced-http

Hi,

I Got this error when I try to install the plugin in my ionic app

cordova plugin add cordova-plugin-advanced-http --save
✖ Running command - failed!
[ERROR] An error occurred while running cordova plugin add cordova-plugin-advanced-http --save (exit code 1):

    Error: Failed to fetch plugin cordova-plugin-advanced-http via registry.
    Probably this is either a connection problem, or plugin spec is incorrect.
    Check your connection and plugin name/version/URL.
    Error: npm: Command failed with exit code 1 Error output:
    cp: node_modules/umd-tough-cookie/lib/umd-tough-cookie.js: No such file or directory
    
    npm ERR! Darwin 16.7.0
    npm ERR! argv "/usr/local/bin/node" 
    "/Users/kevinhuron/Documents/ePressPack/mobile-app-v2/eppMobileV2/node_modules/.bin/npm" "run" "build"
    npm ERR! node v7.1.0
    npm ERR! npm  v2.15.12
    npm ERR! code ELIFECYCLE
    npm ERR! [email protected] build: `cp node_modules/umd-tough-cookie/lib/umd-tough-cookie.js 
    www/umd-tough-cookie.js`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the [email protected] build script 'cp 
    node_modules/umd-tough-cookie/lib/umd-tough-cookie.js www/umd-tough-cookie.js'.
    npm ERR! This is most likely a problem with the cordova-plugin-advanced-http package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR!     cp node_modules/umd-tough-cookie/lib/umd-tough-cookie.js www/umd-tough-cookie.js
    npm ERR! You can get information on how to open an issue for this project with:
    npm ERR!     npm bugs cordova-plugin-advanced-http
    npm ERR! Or if that isn't available, you can get their info via:
    npm ERR! 
    npm ERR!     npm owner ls cordova-plugin-advanced-http
    npm ERR! There is likely additional logging output above.
    
    npm ERR! Please include the following file with any support request:
    npm ERR!     
    /Users/kevinhuron/Documents/ePressPack/mobile-app-v2/eppMobileV2/node_modules/cordova-plugin-advanced-http/npm-debug.log
    
    npm ERR! addLocalDirectory Could not pack 
    /Users/kevinhuron/Documents/ePressPack/mobile-app-v2/eppMobileV2/node_modules/cordova-plugin-advanced-http to 
    /Users/kevinhuron/.npm/cordova-plugin-advanced-http/1.5.10/package.tgz
    npm ERR! addLocal Could not install 
    /Users/kevinhuron/Documents/ePressPack/mobile-app-v2/eppMobileV2/node_modules/cordova-plugin-advanced-http
    npm ERR! Darwin 16.7.0
    npm ERR! argv "/usr/local/bin/node" 
    "/Users/kevinhuron/Documents/ePressPack/mobile-app-v2/eppMobileV2/node_modules/.bin/npm" "install" 
    "cordova-plugin-advanced-http" "--save"
    npm ERR! node v7.1.0
    npm ERR! npm  v2.15.12
    npm ERR! code ELIFECYCLE
    npm ERR! [email protected] prepublish: `npm run build`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the [email protected] prepublish script 'npm run build'.
    npm ERR! This is most likely a problem with the cordova-plugin-advanced-http package,
    npm ERR! not with npm itself.
    npm ERR! Tell the author that this fails on your system:
    npm ERR!     npm run build
    npm ERR! You can get information on how to open an issue for this project with:
    npm ERR!     npm bugs cordova-plugin-advanced-http
    npm ERR! Or if that isn't available, you can get their info via:
    npm ERR! 
    npm ERR!     npm owner ls cordova-plugin-advanced-http
    npm ERR! There is likely additional logging output above.
    
    npm ERR! Please include the following file with any support request:
    npm ERR!     /Users/kevinhuron/Documents/ePressPack/mobile-app-v2/eppMobileV2/node_modules/npm-debug.log

Ionic Info :
cli packages: (/usr/local/lib/node_modules)

@ionic/cli-utils  : 1.12.0
ionic (Ionic CLI) : 3.12.0

global packages:

cordova (Cordova CLI) : 7.0.1 

local packages:

@ionic/app-scripts : 2.1.4
Cordova Platforms  : android 6.1.2 ios 4.3.1
Ionic Framework    : ionic-angular 3.6.1

System:

Android SDK Tools : 25.2.5
ios-deploy        : 1.9.1 
Node              : v7.1.0
npm               : 2.15.12 
OS                : macOS Sierra
Xcode             : Xcode 9.0 Build version 9A235 

Misc:

backend : legacy

I tried ionic cordova plugin add cordova-plugin-advanced-http command : not working
and cordova plugin add cordova-plugin-advanced-http : not working

Thank you very much

PATCH method broken on android

Broken in Android using version 1.6.0, here's the error message:

com/synconset/cordovahttp/CordovaHttpPlugin.java:68: error: constructor CordovaHttpPatch in class CordovaHttpPatch cannot be applied to given types;

        CordovaHttpPatch patch = new CordovaHttpPatch(urlString, params, serializerName, 
 headers, callbackContext);
                                 ^
   required: String,JSONObject,String,JSONObject,CallbackContext,int
   found: String,JSONObject,String,JSONObject,CallbackContext
   reason: actual and formal argument lists differ in length

Receiving different structure of data between iOS and Android when using "urlencoded" serializer

Hello,

I'm having a problem with the post method of the plugin, There is a difference in the data structure sent from the iOS and Android client.
This is the function that sends the post request:

getEventsDetails(eventMemberIds) {
    return new Promise((resolve, reject) => {
      let data = {
        emIds: eventMemberIds
      };
      this.http.post('getEventsDetails', data).then((response: string) => {
        resolve(JSON.parse(response));
      }).catch((err) => reject(err));
    });
  }

In the server side this is what I receive:

image

Not working for ios 11

I use cordova.plugin.http.post and it keep go to error response. ios 10 and below work fine.

Post Request Never Executes, No Response Returned

I posted this issue on Ionic Forum, but since it's likely a plugin issue thought I'd post it here as well.

I'm using Ionic Native HTTP plugin 4.3.2 with Ionic Angular 3.7.1 on iOS 11 to POST data to a server. However the request never seems to get executed, it never gets back a HTTPResponse or even an error.

let url = "https://myserver.com";
let params = { name: 'Me' };
let headers = { 'Accept': 'application/json;charset=UTF-8' };
this.http.post(url, params, headers)
  .then((response:HTTPResponse) => {
    console.log(`Response ${response.data}`);
  })
  .catch((error:any) => {
    console.error(`Error ${error}`);
  });

Doing a GET request works fine returns back a HTTPResponse, just POST that doesn't seem to work.

I tried to POST to different servers to rule out whether it was a server side issue. Did something break in a recent update of the plugin?

Issues with Android & iOS on Phonegap

Not sure what could be going wrong here, but I cannot get this plugin to work on Android. The error I'm receiving is that cordova.plugin is undefined. I've tested this within a handler on the deviceready event, I also set an interval to continually check if it becomes defined, but it does not.

Here is part of my config.xml:

<engine name="android" spec="^6.2.3" />
<engine name="ios" spec="^4.4.0" />
<plugin name="cordova-plugin-advanced-http" spec="^1.5.9" />

No PATCH request support

First of all, thanks for developing this handy plugin.

Would it be possible to add the support for the HTTP PATCH request method? It would be great and it would allow interacting with RESTful APIs more easily.

Thanks again.

iOS: white-list of allowed content-types should be removed

On iOS responses are checked against a list of allowed content types whereas on Android every content type is allowed.
This is only causing problems, because people are confused receiving an error while having a HTTP status code 200 (e.g. #51). We should remove the white-list and just allow every kind of content type.

setDataSerializer fails

It appears that at some point a refactoring changed everything to setDataSerializer from setParamSerializer but this was missed in the angular integration:

http.setParamSerializer is not a function. (In 'http.setParamSerializer(serializer)', 'http.setParamSerializer' is undefined)
http://localhost:8100/plugins/cordova-plugin-advanced-http/www/angular-integration.js:46

cordova.plugin.http.setCookie went wrong

plugin version: 1.9.0
cordova version: 6.5.0
cordova platform versions: android 6.2.3
which platforms are affected:android
example snippet of code:

cordova.plugin.http.setCookie(this.apiAccountUrl, { "sessionid": "" }, {
            http: false,
            secure: true,
            now: new Date(),
            ignoreError: false
        });

these code went wrong with error:
str.trim is not a function

Accept All Certs seems to not work with self signed certificates

We use on a local installed machine a webserver where we install our osgi bundl with our REST apis.
So we can not work with certificates, and also we can not install a signed certifcate, but we have installed a self signed one.

If we use accaptAllCerts with false obvisouly we get this error
{error: "SSL handshake failed", status: 500}
but if we set it to true we get another error
{error: "There was an error with the request", status: 500}

But it should work right?

XCSRF token handling

cordova-plugin-advanced-http doesn't have a header to send csrf token in post request to sap gateway..is there any solution?

clearCookies doesn't take effect

I run the code
cordova.plugin.http.clearCookies();
However the cookie still exists.
The server still get the cookie so I failed to achieve my function.
also,the setCookie function went with errors.
How can I fully control my cookies?

SSL Pining is working after removing certificate.

Hi,

First of all SSL Pining is working as expected but for the first time like we add certificate and run the application, it works but if we remove certificate and re-run the app than it again works and get the success response. Ideally it shouldn't work as i have removed the certificate file from assets folder.

Session cookies not present in file download requests

Hi,

I am using the plugin for downloading files from a secured endpoint via HTTP only session cookies. Any requests following the login work and do forward any session cookies set. However, this does not seem to be the case when it comes to file download requests.

New Version 1.5.8 is not installable

On trying to install latest version with this command

cordova plugin add [email protected] --save

we get this error

[ERROR] An error occurred while running cordova plugin add [email protected] --save (exit code 1):

        
        Installing "cordova-plugin-advanced-http" for android
        Installing "cordova-plugin-file" for android
        Installing "cordova-plugin-compat" for android
        ANDROID_HOME=/home/abc/software/android/sdk
        JAVA_HOME=/usr/lib/jvm/jdk1.8.0_121
        Subproject Path: CordovaLib
        The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use 
        Task.doLast(Action) instead.
                at build_hglad901zbfl7zbg5bgl3vk5.run(/home/abc/tmp/ionic-3.8.1/platforms/android/build.gradle:137)
        The JavaCompile.setDependencyCacheDir() method has been deprecated and is scheduled to be removed in Gradle 4.0.
        Incremental java compilation is an incubating feature.
        The TaskInputs.source(Object) method has been deprecated and is scheduled to be removed in Gradle 4.0. Please 
        use TaskInputs.file(Object).skipWhenEmpty() instead.
        :clean
        :CordovaLib:clean
        
        BUILD SUCCESSFUL
        
        Total time: 0.9 secs
        
        The Android Persistent storage location now defaults to "Internal". Please check this plugin's README to see if 
        your application needs any changes in its config.xml.
        
        If this is a new application no changes are required.
        
        If this is an update to an existing application that did not specify an "AndroidPersistentFileLocation" you may 
        need to add:
        
               "<preference name="AndroidPersistentFileLocation" value="Compatibility" />"
        
        to config.xml in order for the application to find previously stored files.
                
        Error during processing of action! Attempting to revert...
        Failed to install 'cordova-plugin-advanced-http': CordovaError: Uh oh!
        "/home/abc/tmp/ionic-3.8.1/plugins/cordova-plugin-advanced-http/src/android/com/synconset/cordovahttp/CordovaHttp.java" 
        not found!
             at copyFile (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/lib/pluginHandlers.js:219:36)
             at copyNewFile (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/lib/pluginHandlers.js:250:5)
             at install (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/lib/pluginHandlers.js:43:17)
             at Object.process 
        (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/node_modules/cordova-common/src/ActionStack.js:56:25)
             at PluginManager.doOperation 
        (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/node_modules/cordova-common/src/PluginManager.js:117:20)
             at PluginManager.addPlugin 
        (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/node_modules/cordova-common/src/PluginManager.js:147:17)
             at /home/abc/tmp/ionic-3.8.1/platforms/android/cordova/Api.js:254:18
             at _fulfilled (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/node_modules/q/q.js:854:54)
             at self.promiseDispatch.done 
        (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/node_modules/q/q.js:883:30)
             at Promise.promise.promiseDispatch 
        (/home/abc/tmp/ionic-3.8.1/platforms/android/cordova/node_modules/q/q.js:816:13)
        Error: Uh oh!
        "/home/abc/tmp/ionic-3.8.1/plugins/cordova-plugin-advanced-http/src/android/com/synconset/cordovahttp/CordovaHttp.java" 
        not found!

With version before which is 1.3.7 anything is working without error

API should support adding custom cookies

Hi
I'm try to send to server a request to a SMSession cookie. All works good on Android, but if I use iOS 11cannot achieve that.
Any ideas about it? Thanks

My ionic info are

ionic/cli-utils  : 1.18.0
    ionic (Ionic CLI) : 3.18.0

global packages:

    cordova (Cordova CLI) : 7.0.1 

local packages:

    @ionic/app-scripts : 3.1.0
    Cordova Platforms  : android 6.3.0 ios 4.5.3
    Ionic Framework    : ionic-angular 3.9.2

System:

    Android SDK Tools : 26.1.1
    ios-deploy        : 1.9.2 
    ios-sim           : 6.0.0 
    Node              : v7.8.0
    npm               : 4.2.0 
    OS                : macOS Sierra
    Xcode             : Xcode 9.1 Build version 9B55

Extend behaviour of "setHeader" method

Hi guys!

It would be a nice feature to extend the behaviour of the setHeader method to support different headers for all further requests based on the host part of an URL. The URL parameter should be optional to preserve the current behaviour.

Something like:

function setHeader() {
        var url = '*';
        var header = arguments[0];
        var value = arguments[1];

        if (arguments.length === 3) {
            var url = getHost(arguments[0]); // get the host part of the URL
            var header = arguments[1];
            var value = arguments[2];
        }

        this.headers[url][header] = value;
}

What is your opinion on this?

Support sending UTF-8 encoded strings in body (for use with SOAP API)

Hello I need to consume an api that is made in soap, so the body is an xml like this:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws/">
   <soapenv:Header xmlns:wsa="http://www.w3.org/2005/08/addressing"><wsa:Action>http://ws/api/accesoRequest</wsa:Action><wsa:MessageID>uuid:1792610b-a8f7-4251-9828-f8bf59e51c35</wsa:MessageID></soapenv:Header>
   <soapenv:Body>
      <ws:acceso>
         <!--Optional:-->
         <usuario>TEST</usuario>
         <!--Optional:-->
         <contrasena>TEST</contrasena>
         <codigo_consulta>12342</codigo_consulta>
      </ws:acceso>
   </soapenv:Body>
</soapenv:Envelope>

I send this body as a string:

this.http2.post(SERVER_URL, this.envelopeBuilder(method, this.createXmlBody(method, param)), headers)
          .then(data => {
            console.log("data", data);
            console.log(data.data); // data received by server
            this.parseResponse(data.data, cb);

          }).catch(error => {

            console.log("error", error);
            console.log(error.error); // error message as string
            console.log(error.headers);
            this.parseResponse(null, cb);

          });

this.envelopeBuilder(method, this.createXmlBody(method, param)) give me a string and works fine with http from @ angular / http

but with the http of @ ionic-native / http does not work for me, apparently the body is treated and does not arrive as it is to the server.

I am not using @ angular / http since I have cors problem and I do not handle the backend so I have to use ionic native

I think you could create an option for the
this.http2.setDataSerializer
method that insists that the body is raw

plugin_not_installed error with ionic

Hello,

I am trying to use this plugin on a ionic project. I installed it the way the ionic native doc told me to which is:

$ ionic cordova plugin add cordova-plugin-advanced-http
$ npm install --save @ionic-native/http

Then I used it as follow in my provider:

 constructor( @Inject(EnvVariables) public envVariables, public correspondanceProvider: CorrespondanceProvider, public http1: HTTP, private platform:Platform) {
    this.platform.ready().then(
      () => {
        this.http1.validateDomainName(false);
      }
    );
  }

But as soon as my provider is called I get the error:
2017-08-30 17:03:26.520184+0200 MyApp WARN: Native: tried calling HTTP.post, but the HTTP plugin is not installed.
2017-08-30 17:03:26.520338+0200 MyApp WARN: Install the HTTP plugin: 'ionic cordova plugin add cordova-plugin-advanced-http'

But I have:

cordova plugin ls
✔ Running command - done!
cordova-plugin-advanced-http 1.5.9 "Advanced HTTP plugin"
cordova-plugin-compat 1.1.0 "Compat"
cordova-plugin-console 1.0.5 "Console"
cordova-plugin-device 1.1.4 "Device"
cordova-plugin-file 4.3.3 "File"
cordova-plugin-screen-orientation 2.0.1 "Screen Orientation"
cordova-plugin-secure-storage 2.6.8 "SecureStorage"
cordova-plugin-splashscreen 4.0.3 "Splashscreen"
cordova-plugin-statusbar 2.2.2 "StatusBar"
cordova-plugin-whitelist 1.3.1 "Whitelist"
es6-promise-plugin 4.1.0 "Promise"
ionic-plugin-keyboard 2.2.1 "Keyboard"
phonegap-plugin-barcodescanner 6.0.8 "BarcodeScanner"

Is there another way to install the plugin or am I doing something wrong?

Thanks

Ionic info:
cli packages:

@ionic/cli-utils  : 1.6.0 (/Users/jde/Documents/Fork/PRI1701/appliPrintemps/node_modules/ionic/node_modules/@ionic/cli-utils)
ionic (Ionic CLI) : 3.6.0 (/Users/jde/Documents/Fork/PRI1701/appliPrintemps/node_modules/ionic)

global packages:

Cordova CLI : 7.0.1 

local packages:

@ionic/app-scripts              : 2.0.2
@ionic/cli-plugin-cordova       : 1.4.1
@ionic/cli-plugin-ionic-angular : 1.3.2
Cordova Platforms               : android 6.2.3 browser 4.1.0 ios 4.4.0
Ionic Framework                 : ionic-angular 3.5.3

System:

Node       : v6.11.0
OS         : macOS Sierra
Xcode      : Xcode 8.3.3 Build version 8E3004b 
ios-deploy : 1.9.1 
npm        : 3.10.10 

acceptAllCerts on iOS not working

When setting acceptAllCerts to true every request via https returns an error with {"status": -1, "error": "cancelled"}

my code

if(isDevMode()) {
  this.http.acceptAllCerts(true).then(
    () => console.warn("ALL CERTS WILL BE ACCEPTED!"),
    () => console.error("ERROR SETTING acceptAllCerts")
  );
}

During development I used to set the option acceptAllCerts to true.
I migrated to ionic 3.7 and from https://github.com/Telerik-Verified-Plugins/SecureHTTP to this plugin (version 1.6.1) as this is now the official ionic-native http plugin and has all the features that made me use SecureHTTP instead of the previous official ionic-native http plugin.
With the old plugin and ionic 3.6 it was never a problem on iOS 10 and after upgrading suddenly nothing worked anymore. Took me a few hours to identify acceptAllCerts as the culprit.

As a workaround I just do no longer use acceptAllCerts in development and test against servers with "proper" certificates.

It would be nice for this to get fixed, or at least have a comment in the docs warning that the option won't work on iOS

support for typescript

Hi,

It's not really an issue but rather a request if you plan to support typescript?

Thank you and Regards,
Cornelius

"uploadFile" method doesn't return data object on iOS

After execution of UploadFile method it returns only 'headers' and 'status' keys. File has been uploaded but app don't receive 'data' key with data from server.

code example:

let seq = this.http.uploadFile(this.url + '/' + endpoint, {}, {}, file_uri, "photo");

    seq
      .then(response => {
        console.log("Response:", response);
      )
      .catch(err => {});

response log:

Object
headers: Object
  connection: "keep-alive"
  content-encoding: "gzip"
  content-type: "application/json; charset=utf-8"
  date: "Fri, 06 Oct 2017 21:23:37 GMT"
  server: "nginx/1.2.7"
  strict-transport-security: "max-age=15552000"
  transfer-encoding: "Identity"
  vary: "Authorization, Cookie"
status: 200

Same server but uploading with cordova-plugin-file-transfer. Response data exists in response object:

const fileTransfer: TransferObject = this.transfer.create();
    let transferOptions: FileUploadOptions = {
       fileKey: 'photo',
       fileName: file_uri.substr(file_uri.lastIndexOf('/') + 1)
    }
    fileTransfer.upload(file_uri, this.url + '/photo/', transferOptions).then(data => {
      let res = JSON.parse(data.response);
      if (res.success) {
        this.setProfilePhoto(res.photo);
      }
    }, err => {});

Requests are not responding on iOS with non-string values in header object

Firstly, thank you so much for this plugin. It's the only usable plugin for these kind of requirements.

I noticed a little, but a frustrating issue on iOS. If there is non string value in header object, plugin returns nothing. I didn't stumble upon the same issue on Android however. It works well on there.
For example:

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

works well. However, if we change "someVar"s value into integer 2, using like this:

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

That's not working. I'm changing all of the header values to string but, you may want to handle this exception.

Thank you again!

Self Signed certificate pinning is not possible on iOS with ionic

Hello,

I have an issue concerning SSLPinning on iOS with ionic. My code is working well on android but I cannot make it work on iOS. Here is my code:

@Injectable()

@Component({
  providers: [CorrespondanceProvider]
})

export class ProductProvider {
...
  constructor(@Inject(EnvVariables) public envVariables, public http1: HTTP, private platform:Platform) {
    this.platform.ready().then(
      () => {
        this.http1.validateDomainName(false)
        .then(() => this.http1.acceptAllCerts(false)
        .then(() => this.http1.enableSSLPinning(true)
        .then(() => this.http1.setDataSerializer("json"))));
       }
    );
  }

canLog(credentials, url){
    if (this.data){
      return Promise.resolve(this.data);
    }
    let header = { 'Content-Type' : 'application/json'};
    let body = {
            "credentials":{
                "username": credentials.username, 
                 "password": credentials.password
            }
          };

    return new Promise((resolve, reject) => { 
      this.http1.post(`${this.envVariables.Endpoint}/`+url, body, header)
      .then(response => {
        this.data = JSON.parse(response.data);
          resolve(this.data);
      },
      err => reject(err)
      )
    });
  }
}

Each time I make a request I get the following error: {"status":-1,"error":"cancelled"} which seems to correspond to a -999 error in AFNetworking.

After a little research, I discovered that acceptAllCerts(true) only put securityPolicy.allowInvalidCertificates to true, which means that it can accept also self signed certificates (even with the enableSSLPinning set to true) and nothing else, while in Android, acceptAllCert(true) is the opposite of enableSSLPinning(true). Please tell me if I am wrong, but this is a little confusing.

Therefore I also tried to set acceptAllCert to true in the code above, but I still get the same error.
(the certificate is in the right place in my project and is found correctly, if I do not put enableSSLPinning to true, everything work fine).

Could you please help?

Forward cookies got from HTTP/S call to Websocket call does not work

The plugin works good with session cookies, they are forwarded on every http or https call as expected.

But In our project we use also WebSockets, and we need to forward the cookies get from http/s call with your plugin to the WebSocket call.

If we use native http calls and native websockets calls this is working out of the box, I'm not sure if this should also work in your case, but I don't think so. Also I don't know how you are handling the cookie store and how we can extract the cookie.

So what do you think about it, can we do this with your plugin, should it work, or do you think you can adapt the plugin working for that?

Error: package org.apache.cordova.file does not exist

Build is working fine for IOS however failing for Android, I get this error:

/Users/olaxx/Desktop/Axx/ixx/platforms/android/src/com/synconset/cordovahttp/CordovaHttpDownload.java:18: error: package org.apache.cordova.file does not exist
import org.apache.cordova.file.FileUtils;
                              ^
/Users/olaxx/Desktop/Axx/ixx/platforms/android/src/com/synconset/cordovahttp/CordovaHttpDownload.java:49: error: cannot find symbol
                JSONObject fileEntry = FileUtils.getFilePlugin().getEntryForFile(file);
                                       ^
  symbol:   variable FileUtils
  location: class CordovaHttpDownload

Plugin version 1.8.1

My guess is that it just needs to point to the file plugin correctly

System:

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.9.2
    ionic (Ionic CLI) : 3.9.2

global packages:

    Cordova CLI : 7.0.1 

local packages:

    @ionic/app-scripts : 3.0.0
    Cordova Platforms  : android 6.2.3 ios 4.4.0
    Ionic Framework    : ionic-angular 3.7.1

System:

    ios-sim : 5.0.8 
    Node    : v6.10.2
    npm     : 3.10.10 
    OS      : macOS Sierra
    Xcode   : Xcode 8.3.3 Build version 8E3004b 

Transactions slow compared to direct requests from webview

I am observing slower total transaction times (request start to resolve) now that I have switched from using iOS WebView to WKWebview + Cordova-HTTP transactions provided by this plugin.

Is it expected that transaction times will increase when switching to this plugin?

Thanks!

Cookie handler does not support 'expires' on split cookie function

I found an error on the cookie handler!
in cookie-handler.js on the splitCookieString function you should check also wor 'Expires=' with upper "E", some service use this.

so something like that
if (cookieParts[i].substr(-11, 8) === 'expires=' || 'Expires=') {

Sorry for that, but I'm not good in making a pull request and it takes a lot of time for me, do you think you can do this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.