Compare commits

...

71 Commits

Author SHA1 Message Date
Sefa Ilkimen
c748406090 release v3.0.0 2020-07-14 03:13:05 +02:00
Sefa Ilkimen
dc6cf4d45b chore: fix update-plugin-xml.js 2020-07-14 03:12:29 +02:00
Sefa Ilkimen
7661e02598 chore: accept android sdk licenses 2020-07-14 02:39:59 +02:00
Sefa Ilkimen
20ec4bee31 chore: use node 10.x for TravisCI build 2020-07-14 01:33:22 +02:00
Sefa Ilkimen
4eed89e530 chore: update change log 2020-07-14 00:50:49 +02:00
Sefa Ilkimen
f43b2f9f5c Merge pull request #345 from ikosta/master
fix(): default filename for blob
2020-07-07 17:43:46 +02:00
Konstantinos Tsanakas
7b4d37acd9 Update www/ponyfills.js
Co-authored-by: Sefa Ilkimen <silkimen@users.noreply.github.com>
2020-07-07 11:03:36 +02:00
Konstantinos Tsanakas
ca5306cb47 fix(ponyfills): default filename for blob 2020-07-06 15:23:02 +02:00
Konstantinos Tsanakas
c0c1af5ee6 fix(): default filename for blob 2020-06-25 13:36:38 +02:00
Sefa Ilkimen
42e629e34d chore: update readme 2020-06-25 10:35:29 +02:00
Sefa Ilkimen
3bec8dde5f feat: #158 support removing headers which were previously set via "setHeader" 2020-06-25 10:28:43 +02:00
Sefa Ilkimen
8a3bc17810 chore: update dependencies 2020-06-25 09:35:06 +02:00
Sefa Ilkimen
1eb83478dc - deprecate: #297 drop support for Android < 5.1
- bump version
- remove deprecated functions
2020-06-25 07:47:51 +02:00
Sefa Ilkimen
1f0df54111 workaround #344: disable two specs until https://github.com/postmanlabs/httpbin/issues/617 is fixed 2020-06-25 07:09:53 +02:00
Sefa Ilkimen
ef09e466ec release v2.5.1 2020-06-04 01:32:33 +02:00
Sefa Ilkimen
88de0550f4 chore: update README 2020-05-30 18:39:20 +02:00
Sefa Ilkimen
7f680b07ec chore: update changelog 2020-05-29 05:03:12 +02:00
Sefa Ilkimen
a259e7cf8d Merge branch 'clear-cookies-ios'
# Conflicts:
#	test/e2e-specs.js
2020-05-29 05:00:25 +02:00
Sefa Ilkimen
1e3c9e6645 chore: update changelog 2020-05-29 04:22:50 +02:00
Sefa Ilkimen
e0cf458179 Merge branch 'antikalk-master' 2020-05-29 04:15:02 +02:00
Sefa Ilkimen
4f4e7ffa33 fix: broken handling for empty strings 2020-05-29 04:03:20 +02:00
Sefa Ilkimen
65e4a4d4dc fix: e2e spec "should allow empty response body even though responseType is set #334"
- `cordova.plugin.http.get` does not support passing an options object => using `cordova.plugin.http.sendRequest` instead
- but still fails on test "should return empty body string correctly (GET)"
2020-05-29 03:35:20 +02:00
antikalk
fed2b03cc6 Revert "+ dont manipulate response data"
This reverts commit bfc6ba2008.
2020-05-21 22:41:49 +02:00
antikalk
29e0b385de Merge branch 'master' of https://github.com/antikalk/cordova-plugin-advanced-http 2020-05-16 16:55:10 +02:00
antikalk
bfc6ba2008 + dont manipulate response data 2020-05-16 16:54:58 +02:00
Oliver
060aa088f5 Merge branch 'master' into master 2020-05-15 08:32:03 +02:00
antikalk
e775057389 + added e2e test 2020-05-14 22:22:03 +02:00
antikalk
81874c6bc8 + test if empty response data is handled correctly 2020-05-13 09:13:51 +02:00
antikalk
658bbd8b28 + set data to null if response data is not set 2020-05-13 09:12:59 +02:00
antikalk
a1e4be37d4 + early return pattern 2020-05-13 08:07:13 +02:00
antikalk
5be52d78d1 + handle empty success responses 2020-05-12 14:44:22 +02:00
Sefa Ilkimen
0a23e29403 chore: document X.509 client cert feature 2020-05-02 00:48:52 +02:00
Sefa Ilkimen
6009ae82f7 chore: update readme to prevent confusion on request timeout 2020-05-02 00:06:58 +02:00
Sefa Ilkimen
0bfb81c57f chore: fix browserstack testing for android 2020-05-01 23:56:39 +02:00
Sefa Ilkimen
f8f4bdc9df fix: auth challenge block isn't handling server trust settings correctly 2020-03-05 03:23:28 +01:00
Sefa Ilkimen
d84e3995d2 chore: update appium caps 2020-03-05 02:04:48 +01:00
Sefa Ilkimen
f5597dd176 WIP: implement setClientAuthMode()for iOS 2020-03-05 01:36:27 +01:00
Sefa Ilkimen
b25b7db4be release v2.4.1 2020-02-18 01:04:57 +01:00
Sefa Ilkimen
92be8f8e96 fix #248: clearCookies() does not work on iOS 2020-02-03 03:58:09 +01:00
Sefa Ilkimen
9ffdc5d2eb test: implement e2e test for #248 2020-02-03 03:23:50 +01:00
Sefa Ilkimen
23a98ae491 fix #300: FormData object containing null or undefined value is not serialized correctly 2020-02-03 02:46:31 +01:00
Sefa Ilkimen
ab9dad8f46 Merge branch 'antikalk-master' 2020-02-03 01:38:00 +01:00
Sefa Ilkimen
69344b5357 chore: update changelog 2020-02-03 01:37:21 +01:00
Sefa Ilkimen
c88d1b6cc7 test: implement e2e test for #301 2020-02-03 01:30:28 +01:00
antikalk
b6f369b868 fix for issues #220 and #286
When responseType is set to json, the data should be returned as plain json string, not as a base64 encoded string.
2020-01-29 20:14:06 +01:00
Sefa Ilkimen
39fa17e4ed update changelog 2020-01-27 23:57:45 +01:00
Sefa Ilkimen
5a19c6ad06 Merge branch 'fix/#296-multipart-serializer-on-browser-platform' 2020-01-27 23:45:53 +01:00
Sefa Ilkimen
192059d34e release v2.4.0 2020-01-27 04:49:11 +01:00
Sefa Ilkimen
7193b636f1 feat #283: improve error message on timeout on browser platform 2020-01-27 04:44:13 +01:00
Sefa Ilkimen
662b4352f5 update readme and changelog 2020-01-27 02:58:45 +01:00
Sefa Ilkimen
e18f9eee51 implement feat #155 for iOS 2020-01-27 02:22:29 +01:00
Sefa Ilkimen
c7eb60e670 implement feat #155 for android 2020-01-27 02:10:32 +01:00
Sefa Ilkimen
6a930de82f implement www interface for #155 2020-01-27 02:10:01 +01:00
Sefa Ilkimen
588e4a0e57 implement e2e specs for #155 2020-01-27 02:09:21 +01:00
Sefa Ilkimen
78db1dc516 fix #296: [Bug] [browser] multipart requests are not serialized correctly 2020-01-27 01:29:04 +01:00
Sefa Ilkimen
aded59e3d1 implement raw serializer support for browser target 2020-01-26 18:41:31 +01:00
Sefa Ilkimen
9ef582b37f Merge branch 'chuchuva-raw-request-body' 2020-01-26 18:00:47 +01:00
Sefa Ilkimen
33fea67603 update readme and changelog 2020-01-26 17:55:04 +01:00
Sefa Ilkimen
faffe0e078 fix e2e tests for raw serializer 2020-01-26 17:50:40 +01:00
Sefa Ilkimen
99c7f5d331 add default content type for raw serializer 2020-01-26 17:50:18 +01:00
Pavel Chuchuva
b74ad73742 Add documentation for 'raw' serializer 2020-01-18 08:44:58 +11:00
Pavel Chuchuva
7fd7ab223c Add tests for 'raw' serializer 2020-01-18 08:23:43 +11:00
Pavel Chuchuva
937010bd4e Add support for sending 'raw' requests on iOS too 2020-01-14 16:09:47 +11:00
Pavel Chuchuva
7ab4b634ca Add support for sending 'raw' requests on Android
request.data can be `Uint8Array` or `ArrayBuffer`. The plugin will send it as is, without any processing.
2020-01-12 08:18:02 +11:00
Sefa Ilkimen
32187a12fe chore: fix #281 broken builds in forks 2019-12-15 05:18:58 +01:00
Sefa Ilkimen
a4f121728c release v2.3.1 2019-12-14 04:36:31 +01:00
Sefa Ilkimen
21d991b04e chore: setup testing android version on BrowserStack 2019-12-14 04:09:11 +01:00
Sefa Ilkimen
31b1eee355 chore: update version and changelog 2019-12-14 02:15:49 +01:00
Sefa Ilkimen
3d1b195831 Merge pull request #275 from ath0mas/patch-1
Fix WebStorageCookieStore getAllCookies()
2019-12-14 02:08:23 +01:00
Alexis THOMAS
014753e127 fix(cookieStore): error in getAllCookies
typo in Array.prototype call was throwing a TypeError
2019-12-05 15:38:30 +01:00
Sefa Ilkimen
5ee26bc2cc Update badges in readme 2019-12-02 02:46:21 +01:00
34 changed files with 5424 additions and 5639 deletions

View File

@@ -36,6 +36,9 @@ jobs:
build-android:
runs-on: ubuntu-latest
env:
BROWSERSTACK_USERNAME: ${{ secrets.BROWSERSTACK_USERNAME }}
BROWSERSTACK_ACCESS_KEY: ${{ secrets.BROWSERSTACK_ACCESS_KEY }}
steps:
- uses: actions/checkout@v1
- name: Install Node.js ${{ env.nodejs }}
@@ -53,4 +56,10 @@ jobs:
- name: Add workaround for mipsel reference
run: sudo mkdir -p $ANDROID_HOME/ndk-bundle/toolchains/mips64el-linux-android-4.9/prebuilt/linux-x86_64
- name: Build test app
run: scripts/build-test-app.sh --android --emulator
run: scripts/build-test-app.sh --android --device
- name: Upload artifact to BrowserStack
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/upload-browserstack.sh --android
- name: Run e2e tests
if: env.BROWSERSTACK_USERNAME != ''
run: scripts/test-app.sh --android --device

View File

@@ -27,7 +27,7 @@ matrix:
- npm run testjs &&
npm run updatecert &&
scripts/build-test-app.sh --ios --emulator &&
scripts/upload-artifact.sh --ios &&
scripts/upload-saucelabs.sh --ios &&
scripts/test-app.sh --ios --emulator;
- name: "Android Build & Test"
@@ -36,17 +36,19 @@ matrix:
android:
components:
- tools
- platform-tools
- build-tools-28.0.3
- android-27
- android-28
- extra-android-support
- extra-android-m2repository
- extra-google-m2repository
before_install:
- export LANG=en_US.UTF-8 &&
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - &&
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash - &&
sudo apt-get install -y nodejs
- yes | sdkmanager --update
install:
- npm install
@@ -55,5 +57,5 @@ matrix:
- npm run testjs &&
npm run updatecert &&
scripts/build-test-app.sh --android --emulator &&
scripts/upload-artifact.sh --android &&
scripts/upload-saucelabs.sh --android &&
scripts/test-app.sh --android --emulator;

View File

@@ -1,5 +1,40 @@
# Changelog
## 3.0.0
- Feature #158: support removing headers which were previously set via "setHeader"
- Fixed #345: empty file names are not handled correctly (thanks ikosta)
- :warning: **Breaking Change**: Dropped support for Android < 5.1
- :warning: **Breaking Change**: Removed "disableRedirect", use "setFollowRedirect" instead
- :warning: **Breaking Change**: Removed "setSSLCertMode", use "setServerTrustMode" instead
## 2.5.1
- Fixed #334: empty JSON response triggers error even though request is successful (thanks antikalk)
- Fixed #248: clearCookies() does not work on iOS
## 2.5.0
- Feature #56: add support for X.509 client certificate based authentication
## 2.4.1
- Fixed #296: multipart requests are not serialized on browser platform
- Fixed #301: data is not decoded correctly when responseType is "json" (thanks antikalk)
- Fixed #300: FormData object containing null or undefined value is not serialized correctly
## 2.4.0
- Feature #291: add support for sending 'raw' requests (thanks to jachstet-sea and chuchuva)
- Feature #155: add OPTIONS method
- Feature #283: improve error message on timeout on browser platform
## 2.3.1
- Fixed #275: getAllCookies() is broken because of a typo (thanks ath0mas)
## 2.3.0
- Feature #101: Support "multipart/form-data" requests (thanks SDA SE Open Industry Solutions)

View File

@@ -1,8 +1,8 @@
Cordova Advanced HTTP
=====================
[![npm version](https://badge.fury.io/js/cordova-plugin-advanced-http.svg)](https://badge.fury.io/js/cordova-plugin-advanced-http)
[![npm version](https://img.shields.io/npm/v/cordova-plugin-advanced-http)](https://www.npmjs.com/package/cordova-plugin-advanced-http?activeTab=versions)
[![MIT Licence](https://img.shields.io/badge/license-MIT-blue?style=flat)](https://opensource.org/licenses/mit-license.php)
[![downloads/month](https://img.shields.io/npm/dm/cordova-plugin-advanced-http.svg)](https://www.npmjs.com/package/cordova-plugin-advanced-http)
[![MIT Licence](https://badges.frapsoft.com/os/mit/mit.png)](https://opensource.org/licenses/mit-license.php)
[![Travis Build Status](https://img.shields.io/travis/silkimen/cordova-plugin-advanced-http/master?label=Travis%20CI)](https://travis-ci.org/silkimen/cordova-plugin-advanced-http)
[![GitHub Build Status](https://img.shields.io/github/workflow/status/silkimen/cordova-plugin-advanced-http/Cordova%20HTTP%20Plugin%20CI/master?label=GitHub%20Actions)](https://github.com/silkimen/cordova-plugin-advanced-http/actions)
@@ -16,6 +16,7 @@ This is a fork of [Wymsee's Cordova-HTTP plugin](https://github.com/wymsee/cordo
- 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](https://issues.apache.org/jira/browse/CB-2415)
## Updates
@@ -60,7 +61,7 @@ cordova.plugin.http.useBasicAuth('user', 'password');
```
### setHeader<a name="setHeader"></a>
Set a header for all future requests to a specified host. Takes a hostname, a header and a value (must be a string value).
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).
```js
cordova.plugin.http.setHeader('Hostname', 'Header', 'Value');
@@ -91,10 +92,21 @@ 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")
* `multipart`: send FormData objects as multipart content in body (content type "multipart/form-data")
* `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](#setHeader)).
@@ -103,7 +115,7 @@ This defaults to `urlencoded`. You can also override the default content type he
:warning: `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.
Set the "read" timeout in seconds. This is the timeout interval to use when waiting for additional data.
```js
cordova.plugin.http.setRequestTimeout(5.0);
@@ -175,11 +187,28 @@ cordova.plugin.http.setServerTrustMode('nocheck', function() {
});
```
### disableRedirect (deprecated)
This function was deprecated in 2.0.9. Use ["setFollowRedirect"](#setFollowRedirect) instead.
### setClientAuthMode<a name="setClientAuthMode"></a>
Configure X.509 client certificate authentication. Takes mode and options. `mode` being one of following values:
### setSSLCertMode (deprecated)
This function was deprecated in 2.0.8. Use ["setServerTrustMode"](#setServerTrustMode) instead.
* `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
```js
// 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.
@@ -196,15 +225,15 @@ Execute a HTTP request. Takes a URL and an options object. This is the internal
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`
* `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](#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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
* `blob`: data is returned as [Blob instance](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
* `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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), returns `null` when response body is empty
* `blob`: data is returned as [Blob instance](https://developer.mozilla.org/en-US/docs/Web/API/Blob), 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
@@ -332,6 +361,9 @@ Execute a DELETE request. Takes a URL, parameters, and headers. See the [post]
### head<a name="head"></a>
Execute a HEAD request. Takes a URL, parameters, and headers. See the [post](#post) documentation for details on what is returned on success and failure.
### options<a name="options"></a>
Execute a OPTIONS request. Takes a URL, parameters, and headers. See the [post](#post) documentation for details on what is returned on success and failure.
### uploadFile<a name="uploadFile"></a>
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](#post) documentation for details on what is returned on success and failure.

10096
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "cordova-plugin-advanced-http",
"version": "2.3.0",
"version": "3.0.0",
"description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
"scripts": {
"updatecert": "node ./scripts/update-e2e-server-cert.js && node ./scripts/update-e2e-client-cert.js",
@@ -50,7 +50,7 @@
"pvsaikrishna",
"cvillerm",
"hideov",
"Mobisys"
"silkimen"
],
"license": "MIT",
"bugs": {
@@ -58,15 +58,12 @@
},
"homepage": "https://github.com/silkimen/cordova-plugin-advanced-http#readme",
"devDependencies": {
"chai": "4.1.2",
"chai-as-promised": "7.1.1",
"colors": "1.1.2",
"cordova": "8.1.2",
"mocha": "4.0.0",
"mock-require": "2.0.2",
"mz": "2.7.0",
"chai": "4.2.0",
"colors": "1.4.0",
"cordova": "9.0.0",
"mocha": "8.0.1",
"umd-tough-cookie": "2.4.3",
"wd": "1.4.1",
"xml2js": "0.4.19"
"wd": "1.12.1",
"xml2js": "0.4.23"
}
}

View File

@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-advanced-http" version="2.3.0">
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-advanced-http" version="3.0.0">
<name>Advanced HTTP plugin</name>
<description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
@@ -31,6 +31,7 @@
</feature>
</config-file>
<header-file src="src/ios/CordovaHttpPlugin.h"/>
<header-file src="src/ios/BinaryRequestSerializer.h"/>
<header-file src="src/ios/BinaryResponseSerializer.h"/>
<header-file src="src/ios/TextResponseSerializer.h"/>
<header-file src="src/ios/TextRequestSerializer.h"/>
@@ -43,6 +44,7 @@
<header-file src="src/ios/AFNetworking/AFURLSessionManager.h"/>
<header-file src="src/ios/SDNetworkActivityIndicator/SDNetworkActivityIndicator.h"/>
<source-file src="src/ios/CordovaHttpPlugin.m"/>
<source-file src="src/ios/BinaryRequestSerializer.m"/>
<source-file src="src/ios/BinaryResponseSerializer.m"/>
<source-file src="src/ios/TextResponseSerializer.m"/>
<source-file src="src/ios/TextRequestSerializer.m"/>
@@ -77,11 +79,8 @@
<source-file src="src/android/com/silkimen/http/HttpRequest.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/JsonUtils.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/KeyChainKeyManager.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/OkConnectionFactory.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/TLSConfiguration.java" target-dir="src/com/silkimen/http"/>
<source-file src="src/android/com/silkimen/http/TLSSocketFactory.java" target-dir="src/com/silkimen/http"/>
<preference name="OKHTTP_VERSION" default="3.10.0"/>
<framework src="com.squareup.okhttp3:okhttp-urlconnection:$OKHTTP_VERSION"/>
</platform>
<platform name="browser">
<config-file target="config.xml" parent="/*">

View File

@@ -3,8 +3,8 @@ set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd ..; pwd )"
if [ $CI == "true" ] && ([ -z $SAUCE_USERNAME ] || [ -z $SAUCE_ACCESS_KEY ]); then
echo "Skipping CI tests, because Saucelabs credentials are not set.";
if [ $CI == "true" ] && ([ -z $SAUCE_USERNAME ] || [ -z $SAUCE_ACCESS_KEY ]) && ([ -z $BROWSERSTACK_USERNAME ] || [ -z $BROWSERSTACK_ACCESS_KEY ]); then
echo "Skipping CI tests, because Saucelabs and BrowserStack credentials are not set.";
exit 0;
fi

View File

@@ -1,5 +1,5 @@
const args = process.argv.slice(2);
const fs = require('mz/fs');
const fs = require('fs');
const path = require('path');
const xml2js = require('xml2js');
const xmlPath = path.join(__dirname, '..', 'plugin.xml');
@@ -22,10 +22,12 @@ const stringify = obj => {
return builder.buildObject(obj);
};
fs.readFile(xmlPath, 'utf-8')
.then(xml => parse(xml))
.then(parsed => {
parsed.plugin.$.version = args[0];
const update = async (version) => {
const xml = fs.readFileSync(xmlPath, 'utf-8');
const parsed = await parse(xml);
return fs.writeFile(xmlPath, stringify(parsed));
});
parsed.plugin.$.version = version;
fs.writeFileSync(xmlPath, stringify(parsed));
};
return update(args[0]);

33
scripts/upload-browserstack.sh Executable file
View File

@@ -0,0 +1,33 @@
#!/usr/bin/env bash
set -e
PLATFORM=$([[ "${@#--android}" = "$@" ]] && echo "ios" || echo "android")
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd ..; pwd )"
TEMP=$ROOT/temp
if [ -z $BROWSERSTACK_USERNAME ] || [ -z $BROWSERSTACK_ACCESS_KEY ]; then
echo "Skipping uploading artifact, because BrowserStack credentials are not set.";
exit 0;
fi
if [ $PLATFORM = "android" ]; then
curl -u $BROWSERSTACK_USERNAME:$BROWSERSTACK_ACCESS_KEY \
-X POST \
https://api-cloud.browserstack.com/app-automate/upload \
-F "file=@$TEMP/platforms/android/app/build/outputs/apk/debug/app-debug.apk" \
-F "data={\"custom_id\": \"HttpTestAppAndroid\"}"
else
rm -rf $TEMP/HttpDemo.ipa
pushd $TEMP/platforms/ios/build/emulator
rm -rf ./Payload
mkdir -p ./Payload
cp -r ./HttpDemo.app ./Payload/HttpDemo.app
zip -r $TEMP/HttpDemo.ipa ./Payload
popd
curl -u $BROWSERSTACK_USERNAME:$BROWSERSTACK_ACCESS_KEY \
-X POST \
https://api-cloud.browserstack.com/app-automate/upload \
-F "file=@$TEMP/HttpDemo.ipa" \
-F "data={\"custom_id\": \"HttpTestAppIos\"}"
fi

View File

@@ -16,7 +16,6 @@ import com.silkimen.http.HttpBodyDecoder;
import com.silkimen.http.HttpRequest;
import com.silkimen.http.HttpRequest.HttpRequestException;
import com.silkimen.http.JsonUtils;
import com.silkimen.http.OkConnectionFactory;
import com.silkimen.http.TLSConfiguration;
import org.apache.cordova.CallbackContext;
@@ -124,7 +123,6 @@ abstract class CordovaHttpBase implements Runnable {
request.readTimeout(this.timeout);
request.acceptCharset("UTF-8");
request.uncompress(true);
HttpRequest.setConnectionFactory(new OkConnectionFactory());
if (this.tlsConfiguration.getHostnameVerifier() != null) {
request.setHostnameVerifier(this.tlsConfiguration.getHostnameVerifier());
@@ -143,6 +141,8 @@ abstract class CordovaHttpBase implements Runnable {
request.contentType("application/json", "UTF-8");
} else if ("utf8".equals(this.serializer)) {
request.contentType("text/plain", "UTF-8");
} else if ("raw".equals(this.serializer)) {
request.contentType("application/octet-stream");
} else if ("urlencoded".equals(this.serializer)) {
// intentionally left blank, because content type is set in HttpRequest.form()
} else if ("multipart".equals(this.serializer)) {
@@ -159,6 +159,8 @@ abstract class CordovaHttpBase implements Runnable {
request.send(this.data.toString());
} else if ("utf8".equals(this.serializer)) {
request.send(((JSONObject) this.data).getString("text"));
} else if ("raw".equals(this.serializer)) {
request.send(Base64.decode((String)this.data, Base64.DEFAULT));
} else if ("urlencoded".equals(this.serializer)) {
request.form(JsonUtils.getObjectMap((JSONObject) this.data));
} else if ("multipart".equals(this.serializer)) {
@@ -189,7 +191,7 @@ abstract class CordovaHttpBase implements Runnable {
response.setHeaders(request.headers());
if (request.code() >= 200 && request.code() < 300) {
if ("text".equals(this.responseType)) {
if ("text".equals(this.responseType) || "json".equals(this.responseType)) {
String decoded = HttpBodyDecoder.decodeBody(outputStream.toByteArray(), request.charset());
response.setBody(decoded);
} else {

View File

@@ -57,6 +57,8 @@ public class CordovaHttpPlugin extends CordovaPlugin {
return this.executeHttpRequestWithoutData(action, args, callbackContext);
} else if ("delete".equals(action)) {
return this.executeHttpRequestWithoutData(action, args, callbackContext);
} else if ("options".equals(action)) {
return this.executeHttpRequestWithoutData(action, args, callbackContext);
} else if ("post".equals(action)) {
return this.executeHttpRequestWithData(action, args, callbackContext);
} else if ("put".equals(action)) {

View File

@@ -1,26 +0,0 @@
package com.silkimen.http;
import okhttp3.OkHttpClient;
import okhttp3.OkUrlFactory;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URLStreamHandler;
import java.net.Proxy;
public class OkConnectionFactory implements HttpRequest.ConnectionFactory {
private final OkHttpClient client = new OkHttpClient();
public HttpURLConnection create(URL url) {
OkUrlFactory urlFactory = new OkUrlFactory(this.client);
return (HttpURLConnection) urlFactory.open(url);
}
public HttpURLConnection create(URL url, Proxy proxy) {
OkHttpClient clientWithProxy = new OkHttpClient.Builder().proxy(proxy).build();
OkUrlFactory urlFactory = new OkUrlFactory(clientWithProxy);
return (HttpURLConnection) urlFactory.open(url);
}
}

View File

@@ -37,6 +37,39 @@ function serializeParams(params) {
}).join('&');
}
function decodeB64(dataString) {
var binarString = atob(dataString);
var bytes = new Uint8Array(binarString.length);
for (var i = 0; i < binarString.length; ++i) {
bytes[i] = binarString.charCodeAt(i);
}
return bytes.buffer;
}
function processMultipartData(data) {
if (!data) return null;
var fd = new FormData();
for (var i = 0; i < data.buffers.length; ++i) {
var buffer = data.buffers[i];
var name = data.names[i];
var fileName = data.fileNames[i];
var type = data.types[i];
if (fileName) {
fd.append(name, new Blob([decodeB64(buffer)], {type: type}), fileName);
} else {
// we assume it's plain text if no filename was given
fd.append(name, atob(buffer));
}
}
return fd;
}
function deserializeResponseHeaders(headers) {
var headerMap = {};
var arr = headers.trim().split(/[\r\n]+/);
@@ -160,16 +193,42 @@ function sendRequest(method, withData, opts, success, failure) {
setDefaultContentType(headers, 'application/x-www-form-urlencoded');
processedData = serializeParams(data);
break;
case 'multipart':
const contentType = getHeaderValue(headers, 'Content-Type');
// intentionally don't set a default content type
// it's set by the browser together with the content disposition string
if (contentType) {
headers['Content-Type'] = contentType;
}
processedData = processMultipartData(data);
break;
case 'raw':
setDefaultContentType(headers, 'application/octet-stream');
processedData = data;
break;
}
xhr.timeout = timeout * 1000;
xhr.responseType = responseType;
setHeaders(xhr, headers);
xhr.onerror = xhr.ontimeout = function () {
xhr.onerror = function () {
return failure(createXhrFailureObject(xhr));
};
xhr.ontimeout = function () {
return failure({
status: -4,
error: 'Request timed out',
url: url,
headers: {}
});
};
xhr.onload = function () {
if (xhr.readyState !== xhr.DONE) return;

View File

@@ -184,6 +184,8 @@
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
[request setHTTPShouldHandleCookies:NO];
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
@@ -232,6 +234,8 @@
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
[request setHTTPShouldHandleCookies:NO];
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
@@ -293,6 +297,8 @@
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer multipartFormRequestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters constructingBodyWithBlock:block error:&serializationError];
[request setHTTPShouldHandleCookies:NO];
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{
@@ -358,6 +364,8 @@
{
NSError *serializationError = nil;
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:method URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:&serializationError];
[request setHTTPShouldHandleCookies:NO];
if (serializationError) {
if (failure) {
dispatch_async(self.completionQueue ?: dispatch_get_main_queue(), ^{

View File

@@ -0,0 +1,8 @@
#import <Foundation/Foundation.h>
#import "AFURLRequestSerialization.h"
@interface BinaryRequestSerializer : AFHTTPRequestSerializer
+ (instancetype)serializer;
@end

View File

@@ -0,0 +1,53 @@
#import "BinaryRequestSerializer.h"
@implementation BinaryRequestSerializer
+ (instancetype)serializer
{
BinaryRequestSerializer *serializer = [[self alloc] init];
return serializer;
}
#pragma mark - AFURLRequestSerialization
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
}
[mutableRequest setHTTPBody: parameters];
}
return mutableRequest;
}
#pragma mark - NSSecureCoding
- (instancetype)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (!self) {
return nil;
}
return self;
}
@end

View File

@@ -5,11 +5,14 @@
@interface CordovaHttpPlugin : CDVPlugin
- (void)setServerTrustMode:(CDVInvokedUrlCommand*)command;
- (void)setClientAuthMode:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;
- (void)put:(CDVInvokedUrlCommand*)command;
- (void)patch:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;
- (void)delete:(CDVInvokedUrlCommand*)command;
- (void)head:(CDVInvokedUrlCommand*)command;
- (void)options:(CDVInvokedUrlCommand*)command;
- (void)uploadFiles:(CDVInvokedUrlCommand*)command;
- (void)downloadFile:(CDVInvokedUrlCommand*)command;

View File

@@ -1,5 +1,6 @@
#import "CordovaHttpPlugin.h"
#import "CDVFile.h"
#import "BinaryRequestSerializer.h"
#import "BinaryResponseSerializer.h"
#import "TextResponseSerializer.h"
#import "TextRequestSerializer.h"
@@ -20,6 +21,7 @@
@implementation CordovaHttpPlugin {
AFSecurityPolicy *securityPolicy;
NSURLCredential *x509Credential;
}
- (void)pluginInitialize {
@@ -31,11 +33,40 @@
manager.requestSerializer = [AFJSONRequestSerializer serializer];
} else if ([serializerName isEqualToString:@"utf8"]) {
manager.requestSerializer = [TextRequestSerializer serializer];
} else if ([serializerName isEqualToString:@"raw"]) {
manager.requestSerializer = [BinaryRequestSerializer serializer];
} else {
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
}
}
- (void)setupAuthChallengeBlock:(AFHTTPSessionManager*)manager {
[manager setSessionDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(
NSURLSession * _Nonnull session,
NSURLAuthenticationChallenge * _Nonnull challenge,
NSURLCredential * _Nullable __autoreleasing * _Nullable credential
) {
if ([challenge.protectionSpace.authenticationMethod isEqualToString: NSURLAuthenticationMethodServerTrust]) {
*credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
if (![self->securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
return NSURLSessionAuthChallengeRejectProtectionSpace;
}
if (credential) {
return NSURLSessionAuthChallengeUseCredential;
}
}
if ([challenge.protectionSpace.authenticationMethod isEqualToString: NSURLAuthenticationMethodClientCertificate] && self->x509Credential) {
*credential = self->x509Credential;
return NSURLSessionAuthChallengeUseCredential;
}
return NSURLSessionAuthChallengePerformDefaultHandling;
}];
}
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager {
[headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[manager.requestSerializer setValue:obj forHTTPHeaderField:key];
@@ -59,7 +90,7 @@
}
- (void)setResponseSerializer:(NSString*)responseType forManager:(AFHTTPSessionManager*)manager {
if ([responseType isEqualToString: @"text"]) {
if ([responseType isEqualToString: @"text"] || [responseType isEqualToString: @"json"]) {
manager.responseSerializer = [TextResponseSerializer serializer];
} else {
manager.responseSerializer = [BinaryResponseSerializer serializer];
@@ -144,7 +175,6 @@
- (void)executeRequestWithoutData:(CDVInvokedUrlCommand*)command withMethod:(NSString*) method {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *headers = [command.arguments objectAtIndex:1];
@@ -153,6 +183,7 @@
NSString *responseType = [command.arguments objectAtIndex:4];
[self setRequestSerializer: @"default" forManager: manager];
[self setupAuthChallengeBlock: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect:followRedirect forManager:manager];
@@ -196,7 +227,6 @@
- (void)executeRequestWithData:(CDVInvokedUrlCommand*)command withMethod:(NSString*)method {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *data = [command.arguments objectAtIndex:1];
@@ -207,6 +237,7 @@
NSString *responseType = [command.arguments objectAtIndex:6];
[self setRequestSerializer: serializerName forManager: manager];
[self setupAuthChallengeBlock: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect:followRedirect forManager:manager];
@@ -299,16 +330,49 @@
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)get:(CDVInvokedUrlCommand*)command {
[self executeRequestWithoutData: command withMethod:@"GET"];
}
- (void)setClientAuthMode:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult;
NSString *mode = [command.arguments objectAtIndex:0];
if ([mode isEqualToString:@"none"]) {
x509Credential = nil;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
}
if ([mode isEqualToString:@"systemstore"]) {
NSString *alias = [command.arguments objectAtIndex:1];
// TODO
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"mode 'systemstore' is not supported on iOS"];
}
if ([mode isEqualToString:@"buffer"]) {
CFDataRef container = (__bridge CFDataRef) [command.arguments objectAtIndex:2];
CFStringRef password = (__bridge CFStringRef) [command.arguments objectAtIndex:3];
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items;
OSStatus securityError = SecPKCS12Import(container, options, &items);
CFRelease(options);
- (void)delete:(CDVInvokedUrlCommand*)command {
[self executeRequestWithoutData: command withMethod:@"DELETE"];
}
if (securityError != noErr) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
} else {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identity = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
- (void)head:(CDVInvokedUrlCommand*)command {
[self executeRequestWithoutData: command withMethod:@"HEAD"];
self->x509Credential = [NSURLCredential credentialWithIdentity:identity certificates: nil persistence:NSURLCredentialPersistenceForSession];
CFRelease(items);
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
}
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)post:(CDVInvokedUrlCommand*)command {
@@ -323,9 +387,24 @@
[self executeRequestWithData: command withMethod:@"PATCH"];
}
- (void)get:(CDVInvokedUrlCommand*)command {
[self executeRequestWithoutData: command withMethod:@"GET"];
}
- (void)delete:(CDVInvokedUrlCommand*)command {
[self executeRequestWithoutData: command withMethod:@"DELETE"];
}
- (void)head:(CDVInvokedUrlCommand*)command {
[self executeRequestWithoutData: command withMethod:@"HEAD"];
}
- (void)options:(CDVInvokedUrlCommand*)command {
[self executeRequestWithoutData: command withMethod:@"OPTIONS"];
}
- (void)uploadFiles:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *headers = [command.arguments objectAtIndex:1];
@@ -336,6 +415,7 @@
NSString *responseType = [command.arguments objectAtIndex:6];
[self setRequestHeaders: headers forManager: manager];
[self setupAuthChallengeBlock: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect:followRedirect forManager:manager];
[self setResponseSerializer:responseType forManager:manager];
@@ -385,7 +465,6 @@
- (void)downloadFile:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *url = [command.arguments objectAtIndex:0];
@@ -395,6 +474,7 @@
bool followRedirect = [[command.arguments objectAtIndex:4] boolValue];
[self setRequestHeaders: headers forManager: manager];
[self setupAuthChallengeBlock: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect:followRedirect forManager:manager];

View File

@@ -22,9 +22,9 @@
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>
<engine name="android" spec="7.1.0" />
<engine name="browser" spec="5.0.0" />
<engine name="ios" spec="5.0.1" />
<plugin name="cordova-plugin-file" spec="6.0.1" />
<engine name="android" spec="8.1.0" />
<engine name="browser" spec="6.0.0" />
<engine name="ios" spec="5.1.0" />
<plugin name="cordova-plugin-file" spec="6.0.2" />
<preference name="AndroidPersistentFileLocation" value="Internal" />
</widget>

View File

@@ -1,26 +1,26 @@
{
"name": "com.ilkimen.http.demo",
"displayName": "HttpDemo",
"version": "1.0.0",
"description": "A sample Apache Cordova application that demonstrates advanced HTTP plugin.",
"main": "index.js",
"scripts": {
"build": "scripts/build.sh",
"test": "npm run build && scripts/test.sh"
},
"author": "Sefa Ilkimen",
"license": "Apache-2.0",
"dependencies": {
"cordova": "7.0.1",
"cordova-android": "7.1.0",
"cordova-browser": "5.0.0",
"cordova-ios": "5.0.1"
},
"cordova": {
"platforms": [
"android",
"ios"
]
},
"devDependencies": {}
}
"name": "com.ilkimen.http.demo",
"displayName": "HttpDemo",
"version": "1.0.0",
"description": "A sample Apache Cordova application that demonstrates advanced HTTP plugin.",
"main": "index.js",
"scripts": {
"build": "scripts/build.sh",
"test": "npm run build && scripts/test.sh"
},
"author": "Sefa Ilkimen",
"license": "Apache-2.0",
"dependencies": {
"cordova": "9.0.0",
"cordova-android": "8.1.0",
"cordova-browser": "6.0.0",
"cordova-ios": "5.1.0"
},
"cordova": {
"platforms": [
"android",
"ios"
]
},
"devDependencies": {}
}

View File

@@ -2,8 +2,8 @@ const hooks = {
onBeforeEachTest: function (resolve, reject) {
cordova.plugin.http.clearCookies();
helpers.enableFollowingRedirect(function() {
// server trust mode is not supported on brpwser platform
helpers.enableFollowingRedirect(function () {
// server trust mode is not supported on browser platform
if (cordova.platformId === 'browser') {
return resolve();
}
@@ -23,7 +23,7 @@ const helpers = {
setPinnedServerTrustMode: function (resolve, reject) { cordova.plugin.http.setServerTrustMode('pinned', resolve, reject); },
setNoneClientAuthMode: function (resolve, reject) { cordova.plugin.http.setClientAuthMode('none', resolve, reject); },
setBufferClientAuthMode: function (resolve, reject) {
helpers.getWithXhr(function(pkcs) {
helpers.getWithXhr(function (pkcs) {
cordova.plugin.http.setClientAuthMode('buffer', {
rawPkcs: pkcs,
pkcsPassword: 'badssl.com'
@@ -34,8 +34,9 @@ const helpers = {
setUtf8StringSerializer: function (resolve) { resolve(cordova.plugin.http.setDataSerializer('utf8')); },
setUrlEncodedSerializer: function (resolve) { resolve(cordova.plugin.http.setDataSerializer('urlencoded')); },
setMultipartSerializer: function (resolve) { resolve(cordova.plugin.http.setDataSerializer('multipart')); },
setRawSerializer: function (resolve) { resolve(cordova.plugin.http.setDataSerializer('raw')); },
disableFollowingRedirect: function (resolve) { resolve(cordova.plugin.http.setFollowRedirect(false)); },
enableFollowingRedirect: function(resolve) { resolve(cordova.plugin.http.setFollowRedirect(true)); },
enableFollowingRedirect: function (resolve) { resolve(cordova.plugin.http.setFollowRedirect(true)); },
getWithXhr: function (done, url, type) {
var xhr = new XMLHttpRequest();
@@ -70,7 +71,7 @@ const helpers = {
var byteArray = new Uint8Array(buffer);
for (var i = 0; i < byteArray.length; i++) {
hash = ((hash << 5) - hash) + byteArray[i];
hash = ((hash << 5) - hash) + byteArray[i];
hash |= 0; // Convert to 32bit integer
}
@@ -287,25 +288,25 @@ const tests = [
JSON.parse(result.data.data).form.should.eql({ test: 'testString' });
}
},
{
description: 'should resolve correct URL after redirect (GET) #33',
expected: 'resolved: {"status": 200, url: "http://httpbin.org/anything", ...',
func: function (resolve, reject) { cordova.plugin.http.get('http://httpbin.org/redirect-to?url=http://httpbin.org/anything', {}, {}, resolve, reject); },
validationFunc: function (driver, result) {
result.type.should.be.equal('resolved');
result.data.url.should.be.equal('http://httpbin.org/anything');
}
},
{
description: 'should not follow 302 redirect when following redirects is disabled',
expected: 'rejected: {"status": 302, ...',
before: function(resolve, reject) { cordova.plugin.http.disableRedirect(true, resolve, reject)},
func: function (resolve, reject) { cordova.plugin.http.get('http://httpbin.org/redirect-to?url=http://httpbin.org/anything', {}, {}, resolve, reject); },
validationFunc: function (driver, result) {
result.type.should.be.equal('rejected');
result.data.status.should.be.equal(302);
}
},
// {
// description: 'should resolve correct URL after redirect (GET) #33',
// expected: 'resolved: {"status": 200, url: "http://httpbin.org/anything", ...',
// func: function (resolve, reject) { cordova.plugin.http.get('http://httpbin.org/redirect-to?url=http://httpbin.org/anything', {}, {}, resolve, reject); },
// validationFunc: function (driver, result) {
// result.type.should.be.equal('resolved');
// result.data.url.should.be.equal('http://httpbin.org/anything');
// }
// },
// {
// description: 'should not follow 302 redirect when following redirects is disabled',
// expected: 'rejected: {"status": 302, ...',
// before: function (resolve, reject) { cordova.plugin.http.disableRedirect(true, resolve, reject) },
// func: function (resolve, reject) { cordova.plugin.http.get('http://httpbin.org/redirect-to?url=http://httpbin.org/anything', {}, {}, resolve, reject); },
// validationFunc: function (driver, result) {
// result.type.should.be.equal('rejected');
// result.data.status.should.be.equal(302);
// }
// },
{
description: 'should download a file from given URL to given path in local filesystem',
expected: 'resolved: {"content": "<?xml version=\'1.0\' encoding=\'us-ascii\'?>\\n\\n<!-- A SAMPLE set of slides -->" ...',
@@ -373,7 +374,7 @@ const tests = [
var targetUrl = 'http://httpbin.org/post';
helpers.writeToFile(function () {
helpers.writeToFile(function() {
helpers.writeToFile(function () {
cordova.plugin.http.uploadFile(targetUrl, {}, {}, [sourcePath, sourcePath2], [fileName, fileName2], resolve, reject);
}, fileName2, fileContent2);
}, fileName, fileContent);
@@ -463,7 +464,7 @@ const tests = [
}
},
{
description: 'should not send any cookies after running "clearCookies" (GET) #59',
description: 'should not send programmatically set cookies after running "clearCookies" (GET) #59',
expected: 'resolved: {"status": 200, "data": "{\"headers\": {\"Cookie\": \"\"...',
func: function (resolve, reject) {
cordova.plugin.http.setCookie('http://httpbin.org/get', 'myCookie=myValue');
@@ -786,7 +787,7 @@ const tests = [
},
{
description: 'should decode error body even if response type is "arraybuffer"',
expected: 'rejected: {"status": 418, ...',
expected: 'rejected: {"status":418, ...',
func: function (resolve, reject) {
var url = 'https://httpbin.org/status/418';
var options = { method: 'get', responseType: 'arraybuffer' };
@@ -800,7 +801,7 @@ const tests = [
},
{
description: 'should serialize FormData instance correctly when it contains string value',
expected: 'resolved: {"status": 200, ...',
expected: 'resolved: {"status":200, ...',
before: helpers.setMultipartSerializer,
func: function (resolve, reject) {
var ponyfills = cordova.plugin.http.ponyfills;
@@ -819,11 +820,11 @@ const tests = [
},
{
description: 'should serialize FormData instance correctly when it contains blob value',
expected: 'resolved: {"status": 200, ...',
expected: 'resolved: {"status":200, ...',
before: helpers.setMultipartSerializer,
func: function (resolve, reject) {
var ponyfills = cordova.plugin.http.ponyfills;
helpers.getWithXhr(function(blob) {
helpers.getWithXhr(function (blob) {
var formData = new ponyfills.FormData();
formData.append('CordovaLogo', blob);
@@ -843,19 +844,150 @@ const tests = [
const b64Logo = rawLogo.toString('base64');
JSON.parse(result.data.data).files.CordovaLogo.should.be.equal('data:image/png;base64,' + b64Logo);
}
}
},
{
description: 'should send raw byte array correctly (POST) #291',
expected: 'resolved: {"status":200,"data:application/octet-stream;base64,iVBORw0KGgoAAAANSUhEUg ...',
before: helpers.setRawSerializer,
func: function (resolve, reject) {
helpers.getWithXhr(function (buffer) {
cordova.plugin.http.post('http://httpbin.org/anything', buffer, {}, resolve, reject);
}, './res/cordova_logo.png', 'arraybuffer');
},
validationFunc: function (driver, result) {
helpers.checkResult(result, 'resolved');
result.data.status.should.be.equal(200);
// TODO: not ready yet
// {
// description: 'should authenticate correctly when client cert auth is configured with a PKCS12 container',
// expected: 'resolved: {"status": 200, ...',
// before: helpers.setBufferClientAuthMode,
// func: function (resolve, reject) { cordova.plugin.http.get('https://client.badssl.com/', {}, {}, resolve, reject); },
// validationFunc: function (driver, result) {
// result.type.should.be.equal('resolved');
// result.data.data.should.include('TLS handshake');
// }
// }
// httpbin.org encodes posted binaries in base64 and echoes them back
// therefore we need to check for base64 string with mime type prefix
const fs = require('fs');
const rawLogo = fs.readFileSync('./test/e2e-app-template/www/res/cordova_logo.png');
const b64Logo = rawLogo.toString('base64');
const parsed = JSON.parse(result.data.data);
parsed.headers['Content-Type'].should.be.equal('application/octet-stream');
parsed.data.should.be.equal('data:application/octet-stream;base64,' + b64Logo);
}
},
{
description: 'should perform an OPTIONS request correctly #155',
expected: 'resolved: {"status":200,"headers":{"allow":"GET, PUT, DELETE, HEAD, PATCH, TRACE, POST, OPTIONS" ...',
func: function (resolve, reject) { cordova.plugin.http.options('http://httpbin.org/anything', {}, {}, resolve, reject); },
validationFunc: function (driver, result) {
result.type.should.be.equal('resolved');
result.data.status.should.be.equal(200);
result.data.headers.should.be.an('object');
result.data.headers.allow.should.include('GET');
result.data.headers.allow.should.include('PUT');
result.data.headers.allow.should.include('DELETE');
result.data.headers.allow.should.include('HEAD');
result.data.headers.allow.should.include('PATCH');
result.data.headers.allow.should.include('TRACE');
result.data.headers.allow.should.include('POST');
result.data.headers.allow.should.include('OPTIONS');
result.data.headers['access-control-allow-origin'].should.be.equal('*');
}
},
{
description: 'should allow empty response body even though responseType is set #334',
expected: 'resolved: {"status":200, ...',
func: function (resolve, reject) {
var url = 'https://httpbin.org/status/200';
var options = { method: 'get', responseType: 'json' };
cordova.plugin.http.sendRequest(url, options, resolve, reject);
},
validationFunc: function (driver, result) {
result.type.should.be.equal('resolved');
should.equal(null, result.data.data);
}
},
{
description: 'should decode JSON data correctly when response type is "json" #301',
expected: 'resolved: {"status":200,"data":{"slideshow": ... ',
func: function (resolve, reject) {
var url = 'https://httpbin.org/json';
var options = { method: 'get', responseType: 'json' };
cordova.plugin.http.sendRequest(url, options, resolve, reject);
},
validationFunc: function (driver, result) {
result.type.should.be.equal('resolved');
result.data.status.should.be.equal(200);
result.data.data.should.be.an('object');
result.data.data.slideshow.should.be.eql({
author: 'Yours Truly',
date: 'date of publication',
slides: [
{
title: 'Wake up to WonderWidgets!',
type: 'all'
},
{
items: [
'Why <em>WonderWidgets</em> are great',
'Who <em>buys</em> WonderWidgets'
],
title: 'Overview',
type: 'all'
}
],
title: 'Sample Slide Show'
});
}
},
{
description: 'should serialize FormData instance correctly when it contains null or undefined value #300',
expected: 'resolved: {"status":200, ...',
before: helpers.setMultipartSerializer,
func: function (resolve, reject) {
var ponyfills = cordova.plugin.http.ponyfills;
var formData = new ponyfills.FormData();
formData.append('myNullValue', null);
formData.append('myUndefinedValue', undefined);
var url = 'https://httpbin.org/anything';
var options = { method: 'post', data: formData };
cordova.plugin.http.sendRequest(url, options, resolve, reject);
},
validationFunc: function (driver, result) {
helpers.checkResult(result, 'resolved');
result.data.status.should.be.equal(200);
JSON.parse(result.data.data).form.should.be.eql({
myNullValue: 'null',
myUndefinedValue: 'undefined'
});
}
},
{
description: 'should authenticate correctly when client cert auth is configured with a PKCS12 container',
expected: 'resolved: {"status": 200, ...',
before: helpers.setBufferClientAuthMode,
func: function (resolve, reject) { cordova.plugin.http.get('https://client.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function (driver, result) {
result.type.should.be.equal('resolved');
result.data.data.should.include('TLS handshake');
}
},
{
description: 'should not send any cookies after running "clearCookies" (GET) #248',
expected: 'resolved: {"status": 200, "data": "{\"cookies\":{}} ...',
before: helpers.disableFollowingRedirect,
func: function (resolve, reject) {
cordova.plugin.http.get('https://httpbin.org/cookies/set?myCookieKey=myCookieValue', {}, {}, function () {
cordova.plugin.http.clearCookies();
cordova.plugin.http.get('https://httpbin.org/cookies', {}, {}, resolve, reject);
}, function () {
cordova.plugin.http.clearCookies();
cordova.plugin.http.get('https://httpbin.org/cookies', {}, {}, resolve, reject);
});
},
validationFunc: function (driver, result) {
result.type.should.be.equal('resolved');
result.data.status.should.be.equal(200);
JSON.parse(result.data.data).cookies.should.be.eql({});
}
},
];
if (typeof module !== 'undefined' && module.exports) {

View File

@@ -56,6 +56,22 @@ const configs = {
deviceName: 'Android Emulator',
autoWebview: true,
app: 'sauce-storage:HttpDemo.apk'
},
// testing on BrowserStack
browserstackIosDevice: {
device: 'iPhone 7',
os_version: '10',
project: 'HTTP Test App',
autoWebview: true,
app: 'HttpTestAppAndroid'
},
browserstackAndroidDevice: {
device: 'Google Nexus 6',
os_version: '5.0',
project: 'HTTP Test App',
autoWebview: true,
app: 'HttpTestAppAndroid'
}
};

View File

@@ -9,6 +9,11 @@ const configs = {
host: 'ondemand.saucelabs.com',
port: 80,
auth: process.env.SAUCE_USERNAME + ":" + process.env.SAUCE_ACCESS_KEY
},
browserstack: {
host: 'hub-cloud.browserstack.com',
port: 80,
auth: process.env.BROWSERSTACK_USERNAME + ":" + process.env.BROWSERSTACK_ACCESS_KEY
}
}

View File

@@ -1,23 +1,21 @@
const wd = require('wd');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const logging = require('./logging');
const capsConfig = require('./caps');
const serverConfig = require('./server');
const testDefinitions = require('../e2e-specs');
chai.use(chaiAsPromised);
chaiAsPromised.transferPromiseness = wd.transferPromiseness;
global.should = chai.should();
describe('Advanced HTTP e2e test suite', function () {
const isSauceLabs = !!process.env.SAUCE_USERNAME;
const isBrowserStack = !!process.env.BROWSERSTACK_USERNAME;
const isVerbose = process.argv.includes('--verbose');
const isDevice = process.argv.includes('--device');
const isAndroid = process.argv.includes('--android');
const targetInfo = { isSauceLabs, isDevice, isAndroid };
const environment = isSauceLabs ? 'saucelabs' : 'local';
const targetInfo = { isSauceLabs, isBrowserStack, isDevice, isAndroid };
const environment = isSauceLabs ? 'saucelabs' : isBrowserStack ? 'browserstack' : 'local';
let driver;
let allPassed = true;

View File

@@ -1,5 +1,4 @@
const chai = require('chai');
const mock = require('mock-require');
const util = require('util');
const should = chai.should();
@@ -50,6 +49,13 @@ describe('Advanced HTTP public interface', function () {
http.getHeaders('*').myKey.should.equal('myValue');
});
it('clears global headers correctly when value is undefined', () => {
http.setHeader('*', 'myKey', 'myValue');
http.setHeader('*', 'myKey', null);
should.equal(undefined, http.getHeaders('*').myKey);
Object.keys(http.getHeaders('*')).length.should.be.equal(0);
});
it('sets host headers correctly #24', () => {
http.setHeader('www.google.de', 'myKey', 'myValue');
http.getHeaders('www.google.de').myKey.should.equal('myValue');
@@ -419,7 +425,7 @@ describe('Common helpers', function () {
response => response.data.should.be.equal('fakeData')
);
handler({ data: 'fakeData' });
handler({ data: 'fakeData' });
});
it('does not change response data if response type is "text"', () => {
@@ -444,6 +450,17 @@ describe('Common helpers', function () {
handler({ data: JSON.stringify(fakeData) });
});
it('handles empty "json" response correctly', () => {
const emptyData = "";
const helpers = require('../www/helpers')(null, jsUtil, null, messages, null, errorCodes);
const handler = helpers.injectRawResponseHandler(
'json',
response => should.equal(undefined, response.data)
);
handler({ data: emptyData });
});
it('handles response type "arraybuffer" correctly', () => {
const helpers = require('../www/helpers')(null, jsUtil, null, messages, fakeBase64, errorCodes);
const handler = helpers.injectRawResponseHandler(
@@ -454,6 +471,16 @@ describe('Common helpers', function () {
handler({ data: 'myString' });
});
it('handles empty "arraybuffer" response correctly', () => {
const helpers = require('../www/helpers')(null, jsUtil, null, messages, fakeBase64, errorCodes);
const handler = helpers.injectRawResponseHandler(
'arraybuffer',
response => should.equal(null, response.data)
);
handler({ data: '' });
});
it('handles response type "blob" correctly', () => {
const helpers = require('../www/helpers')(null, jsUtil, null, messages, fakeBase64, errorCodes);
const handler = helpers.injectRawResponseHandler(
@@ -465,7 +492,19 @@ describe('Common helpers', function () {
}
);
handler({ data: 'myString', headers: { 'content-type': 'fakeType'} });
handler({ data: 'myString', headers: { 'content-type': 'fakeType' } });
});
it('handles empty "blob" response correctly', () => {
const helpers = require('../www/helpers')(null, jsUtil, null, messages, fakeBase64, errorCodes);
const handler = helpers.injectRawResponseHandler(
'blob',
(response) => {
should.equal(null, response.data)
}
);
handler({ data: '', headers: { 'content-type': 'fakeType' } });
});
it('calls failure callback when post-processing fails', () => {
@@ -546,7 +585,7 @@ describe('Common helpers', function () {
it('processes data correctly when serializer "utf8" is configured', (cb) => {
helpers.processData('myString', 'utf8', (data) => {
data.should.be.eql({text: 'myString'});
data.should.be.eql({ text: 'myString' });
cb();
})
});
@@ -589,6 +628,53 @@ describe('Common helpers', function () {
cb();
});
});
it('processes data correctly when serializer "multipart" is configured and form data contains file value (filename set)', (cb) => {
const formData = new FormDataMock();
formData.append('myFile', new BlobMock([testString], { type: 'application/octet-stream' }), 'file.name');
helpers.processData(formData, 'multipart', (data) => {
data.buffers.length.should.be.equal(1);
data.names.length.should.be.equal(1);
data.fileNames.length.should.be.equal(1);
data.types.length.should.be.equal(1);
data.buffers[0].should.be.eql(testStringBase64);
data.names[0].should.be.equal('myFile');
data.fileNames[0].should.be.equal('file.name');
data.types[0].should.be.equal('application/octet-stream');
cb();
});
});
it('processes data correctly when serializer "multipart" is configured and form data contains file value (filename empty)', (cb) => {
const formData = new FormDataMock();
formData.append('myFile', new BlobMock([testString], { type: 'application/octet-stream' }), '');
helpers.processData(formData, 'multipart', (data) => {
data.buffers.length.should.be.equal(1);
data.names.length.should.be.equal(1);
data.fileNames.length.should.be.equal(1);
data.types.length.should.be.equal(1);
data.buffers[0].should.be.eql(testStringBase64);
data.names[0].should.be.equal('myFile');
data.fileNames[0].should.be.equal('');
data.types[0].should.be.equal('application/octet-stream');
cb();
});
});
it('processes data correctly when serializer "raw" is configured', (cb) => {
const byteArray = new Uint8Array([1, 2, 3]);
helpers.processData(byteArray, 'raw', (data) => {
data.should.be.a('ArrayBuffer');
data.should.be.equal(byteArray.buffer);
cb();
})
});
});
});
@@ -638,7 +724,7 @@ describe('Dependency Validator', function () {
describe('checkFormDataInstance()', function () {
it('throws an error if FormData.entries() is not supported on given instance', function () {
const console = new ConsoleMock();
const validator = require('../www/dependency-validator')({ FormData: {}}, console, messages);
const validator = require('../www/dependency-validator')({ FormData: {} }, console, messages);
(() => validator.checkFormDataInstance({})).should.throw(messages.MISSING_FORMDATA_ENTRIES_API);
});
@@ -675,12 +761,12 @@ describe('Ponyfills', function () {
const iterator = new ponyfills.Iterator([]);
iterator.next().should.be.eql({ done: true, value: undefined });
});
it('returns iteration object correctly when end posititon of list is not reached yet', () => {
const iterator = new ponyfills.Iterator([['first', 'this is the first item']]);
iterator.next().should.be.eql({ done: false, value: ['first', 'this is the first item'] });
});
it('returns iteration object correctly when end posititon of list is already reached', () => {
const iterator = new ponyfills.Iterator([['first', 'this is the first item']]);
iterator.next();

View File

@@ -3,7 +3,7 @@ const BlobMock = require('./Blob.mock');
module.exports = class FileMock extends BlobMock {
constructor(blob, fileName) {
super(blob, { type: blob.type });
this._fileName = fileName || '';
this._fileName = fileName !== undefined ? fileName : 'blob';
this.__lastModifiedDate = new Date();
}

View File

@@ -1,8 +1,8 @@
module.exports = function init(global, jsUtil, cookieHandler, messages, base64, errorCodes, dependencyValidator, ponyfills) {
var validSerializers = ['urlencoded', 'json', 'utf8', 'multipart'];
var validSerializers = ['urlencoded', 'json', 'utf8', 'raw', 'multipart'];
var validCertModes = ['default', 'nocheck', 'pinned', 'legacy'];
var validClientAuthModes = ['none', 'systemstore', 'buffer'];
var validHttpMethods = ['get', 'put', 'post', 'patch', 'head', 'delete', 'upload', 'download'];
var validHttpMethods = ['get', 'put', 'post', 'patch', 'head', 'delete', 'options', 'upload', 'download'];
var validResponseTypes = ['text', 'json', 'arraybuffer', 'blob'];
var interface = {
@@ -187,7 +187,9 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
}
function checkForInvalidHeaderValue(value) {
if (jsUtil.getTypeOf(value) !== 'String') {
var type = jsUtil.getTypeOf(value);
if (type !== 'String' && type !== 'Null') {
throw new Error(messages.INVALID_HEADER_VALUE);
}
@@ -295,20 +297,28 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
try {
// json
if (responseType === validResponseTypes[1]) {
response.data = JSON.parse(response.data);
response.data = response.data === ''
? undefined
: JSON.parse(response.data);
}
// arraybuffer
else if (responseType === validResponseTypes[2]) {
response.data = base64.toArrayBuffer(response.data);
response.data = response.data === ''
? null
: base64.toArrayBuffer(response.data);
}
// blob
else if (responseType === validResponseTypes[3]) {
var buffer = base64.toArrayBuffer(response.data);
var type = response.headers['content-type'] || '';
var blob = new Blob([ buffer ], { type: type });
response.data = blob;
if (response.data === '') {
response.data = null;
} else {
var buffer = base64.toArrayBuffer(response.data);
var type = response.headers['content-type'] || '';
var blob = new Blob([buffer], { type: type });
response.data = blob;
}
}
success(response);
@@ -365,6 +375,8 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
return ['Object'];
case 'json':
return ['Array', 'Object'];
case 'raw':
return ['Uint8Array', 'ArrayBuffer'];
default:
return [];
}
@@ -382,7 +394,7 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
if (allowedInstanceTypes) {
var isCorrectInstanceType = false;
allowedInstanceTypes.forEach(function(type) {
allowedInstanceTypes.forEach(function (type) {
if ((global[type] && data instanceof global[type]) || (ponyfills[type] && data instanceof ponyfills[type])) {
isCorrectInstanceType = true;
}
@@ -400,6 +412,8 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
switch (dataSerializer) {
case 'utf8':
return cb({ text: data });
case 'raw':
return cb(currentDataType === 'Uint8Array' ? data.buffer : data);
case 'multipart':
return processFormData(data, cb);
default:
@@ -436,10 +450,10 @@ module.exports = function init(global, jsUtil, cookieHandler, messages, base64,
if (entry.value[1] instanceof global.Blob || entry.value[1] instanceof global.File) {
var reader = new global.FileReader();
reader.onload = function() {
reader.onload = function () {
result.buffers.push(base64.fromArrayBuffer(reader.result));
result.names.push(entry.value[0]);
result.fileNames.push(entry.value[1].name || 'blob');
result.fileNames.push(entry.value[1].name !== undefined ? entry.value[1].name : 'blob');
result.types.push(entry.value[1].type || '');
processFormDataIterator(iterator, textEncoder, result, onFinished);
};

View File

@@ -6,6 +6,8 @@ module.exports = {
return 'Array';
case '[object Blob]':
return 'Blob';
case '[object Uint8Array]':
return 'Uint8Array';
case '[object ArrayBuffer]':
return 'ArrayBuffer';
case '[object Boolean]':

View File

@@ -146,7 +146,7 @@ module.exports = function init(ToughCookie, _) {
Object.keys(store).forEach(function (domain) {
Object.keys(store[domain]).forEach(function (path) {
Array.protype.push.apply(cookies, _.values(store[domain][path]));
Array.prototype.push.apply(cookies, _.values(store[domain][path]));
});
});

View File

@@ -11,7 +11,7 @@ module.exports = {
INVALID_DATA_SERIALIZER: 'advanced-http: invalid serializer, supported serializers are:',
INVALID_DOWNLOAD_FILE_PATH: 'advanced-http: invalid "filePath" value, needs to be a string, <filePath: string>',
INVALID_FOLLOW_REDIRECT_VALUE: 'advanced-http: invalid follow redirect value, needs to be a boolean value, <followRedirect: boolean>',
INVALID_HEADER_VALUE: 'advanced-http: invalid header value, needs to be a string, <header: string>',
INVALID_HEADER_VALUE: 'advanced-http: invalid header value, needs to be a string or null, <header: string | null>',
INVALID_HTTP_METHOD: 'advanced-http: invalid HTTP method, supported methods are:',
INVALID_RESPONSE_TYPE: 'advanced-http: invalid response type, supported types are:',
INVALID_SSL_CERT_MODE: 'advanced-http: invalid SSL cert mode, supported modes are:',

View File

@@ -16,9 +16,9 @@ module.exports = function init(global) {
} else if (global.Blob && value instanceof global.Blob) {
// mimic File instance by adding missing properties
value.lastModifiedDate = new Date();
value.name = filename || '';
value.name = filename !== undefined ? filename : 'blob';
} else {
value = value.toString ? value.toString() : value;
value = String(value);
}
this.__items.push([ name, value ]);
@@ -44,4 +44,4 @@ module.exports = function init(global) {
}
return interface;
};
};

View File

@@ -14,19 +14,16 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
setRequestTimeout: setRequestTimeout,
getFollowRedirect: getFollowRedirect,
setFollowRedirect: setFollowRedirect,
// @DEPRECATED
disableRedirect: disableRedirect,
// @DEPRECATED
setSSLCertMode: setServerTrustMode,
setServerTrustMode: setServerTrustMode,
setClientAuthMode: setClientAuthMode,
sendRequest: sendRequest,
post: post,
get: get,
put: put,
patch: patch,
get: get,
delete: del,
head: head,
options: options,
uploadFile: uploadFile,
downloadFile: downloadFile,
ErrorCode: errorCodes,
@@ -61,7 +58,12 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
helpers.checkForInvalidHeaderValue(value);
globalConfigs.headers[host] = globalConfigs.headers[host] || {};
globalConfigs.headers[host][header] = value;
if (value === null) {
delete globalConfigs.headers[host][header];
} else {
globalConfigs.headers[host][header] = value;
}
}
function getDataSerializer() {
@@ -104,14 +106,6 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
globalConfigs.followRedirect = helpers.checkFollowRedirectValue(follow);
}
// @DEPRECATED
function disableRedirect(disable, success, failure) {
helpers.handleMissingCallbacks(success, failure);
setFollowRedirect(!disable);
success();
}
function setServerTrustMode(mode, success, failure) {
helpers.handleMissingCallbacks(success, failure);
@@ -153,7 +147,7 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
case 'post':
case 'put':
case 'patch':
return helpers.processData(options.data, options.serializer, function(data) {
return helpers.processData(options.data, options.serializer, function (data) {
exec(onSuccess, onFail, 'CordovaHttpPlugin', options.method, [url, data, options.serializer, headers, options.timeout, options.followRedirect, options.responseType]);
});
case 'upload':
@@ -172,10 +166,6 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
return publicInterface.sendRequest(url, { method: 'post', data: data, headers: headers }, success, failure);
};
function get(url, params, headers, success, failure) {
return publicInterface.sendRequest(url, { method: 'get', params: params, headers: headers }, success, failure);
};
function put(url, data, headers, success, failure) {
return publicInterface.sendRequest(url, { method: 'put', data: data, headers: headers }, success, failure);
}
@@ -184,6 +174,10 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
return publicInterface.sendRequest(url, { method: 'patch', data: data, headers: headers }, success, failure);
}
function get(url, params, headers, success, failure) {
return publicInterface.sendRequest(url, { method: 'get', params: params, headers: headers }, success, failure);
};
function del(url, params, headers, success, failure) {
return publicInterface.sendRequest(url, { method: 'delete', params: params, headers: headers }, success, failure);
}
@@ -192,6 +186,10 @@ module.exports = function init(exec, cookieHandler, urlUtil, helpers, globalConf
return publicInterface.sendRequest(url, { method: 'head', params: params, headers: headers }, success, failure);
}
function options(url, params, headers, success, failure) {
return publicInterface.sendRequest(url, { method: 'options', params: params, headers: headers }, success, failure);
};
function uploadFile(url, params, headers, filePath, name, success, failure) {
return publicInterface.sendRequest(url, { method: 'upload', params: params, headers: headers, filePath: filePath, name: name }, success, failure);
}