Compare commits

...
15 Commits
Author SHA1 Message Date
Sefa Ilkimen 47ac5d3e0a release v1.7.1 2017-10-27 18:48:39 +02:00
Sefa Ilkimen 4db3939bbe - update version number
- update changelog
- enable travis caching for node modules
2017-10-27 16:44:37 +02:00
Sefa Ilkimen 0aee536d5c fix #26: JSON request with array data is not working on Android (JSON error) 2017-10-27 16:20:35 +02:00
Sefa Ilkimen 0d8d7735d9 - improve docu for "setHeader" method
- add test case for "setHeader" call with port number
2017-10-27 12:16:01 +02:00
Sefa Ilkimen 208529003d fix #35: Android headers are not normalized (not returned in lowercase) 2017-10-26 17:34:32 +02:00
Sefa Ilkimen 77c0a887ac fix #36: setting basic authentication not working correctly 2017-10-26 12:11:14 +02:00
Jochen Becker 8c596d80b0 fixed global 'asterisks' header not defined 2017-10-26 11:27:30 +02:00
Sefa Ilkimen 0407a561fc fix broken links in contribution guidelines 2017-10-24 17:07:25 +02:00
Sefa Ilkimen ebe6205e50 add contribution guidelines 2017-10-24 17:00:40 +02:00
Sefa Ilkimen 3ea9fd4fd1 release v1.7.0 2017-10-24 14:08:06 +02:00
Sefa Ilkimen 56791016e6 updated version number 2017-10-24 14:06:19 +02:00
Sefa Ilkimen 9655c89486 - added indicator for running tests
- validation function is triggered when test is finished
2017-10-23 16:54:34 +02:00
Sefa Ilkimen 15bf6281bc added missing documentation for "patch " method 2017-10-20 17:50:16 +02:00
Sefa Ilkimen d342ca054a updated readme and changelog 2017-10-20 17:36:46 +02:00
Sefa Ilkimen d7e13b046b - feature #24: extended behaviour of "setHeader" method
- added test suite for www interface of plugin (js files)
2017-10-20 17:22:51 +02:00
34 changed files with 692 additions and 226 deletions
+1
View File
@@ -1,4 +1,5 @@
node_modules/**
tags
.zedstate
npm-debug.log
/temp
+5 -2
View File
@@ -4,7 +4,9 @@ language: objective-c
os: osx
osx_image: xcode9.1
cache: false
cache:
directories:
- node_modules
addons:
sauce_connect:
@@ -32,7 +34,8 @@ install:
script:
- travis_wait scripts/build-test-app.sh
- scripts/upload-artifact.sh
- scripts/test.sh --ios --emulator
- npm run testjs
- scripts/test-app.sh --ios --emulator
after_success:
+10
View File
@@ -1,5 +1,15 @@
# Changelog
## v1.7.1
- Fixed #36: setting basic authentication not working correctly (thanks jkfb)
- Fixed #35: Android headers are not normalized (not returned in lowercase)
- Fixed #26: JSON request with array data is not working on Android (JSON error)
## v1.7.0
- Feature #24: "setHeader" allows configuring headers for specified host
## v1.6.2
- Change #29: removed "validateDomainName" (see info notice)
+82
View File
@@ -0,0 +1,82 @@
# Contributing to Advanced HTTP Plugin
We'd love for you to contribute to our source code and to make Advanced HTTP even better than it is
today! Here are the guidelines we'd like you to follow:
- [Issues and Bugs](#issue)
- [Feature Requests](#feature)
- [Submission Guidelines](#submit)
## <a name="issue"></a> Found an Issue?
If you find a bug in the source code or a mistake in the documentation, you can help us by
submitting an issue to our [GitHub Repository](https://github.com/silkimen/cordova-plugin-advanced-http/issues).
Even better you can submit a Pull Request with a fix.
## <a name="feature"></a> Want a Feature?
You can request a new feature by submitting an issue to our
[GitHub Repository](https://github.com/silkimen/cordova-plugin-advanced-http/issues).
If you would like to implement a new feature then consider what kind of change it is:
* **Major Changes** that you wish to contribute to the project should be discussed first so that we
can better coordinate our efforts, prevent duplication of work, and help you to craft the change
so that it is successfully accepted into the project. Please submit an issue to our GitHub Repository
for discussion.
* **Small Changes** can be crafted and submitted to the GitHub Repository as a Pull Request.
## <a name="submit"></a> Submission Guidelines
### Submitting an Issue
Before you submit your issue search the archive, maybe your question was already answered.
If your issue appears to be a bug, and hasn't been reported, open a new issue. Help us to maximize
the effort we can spend fixing issues and adding new features, by not reporting duplicate issues.
Providing the following information will increase the chances of your issue being dealt with
quickly:
* **Overview of the Issue** - if an error is being thrown a non-minified stack trace helps
* **Motivation for or Use Case** - explain why this is a bug for you
* **Advanced HTTP Version(s)** - is it a regression?
* **Operating System** - is this a problem with all supported OS or only specific ones?
* **Related Issues** - has a similar issue been reported before?
* **Suggest a Fix** - if you can't fix the bug yourself, perhaps you can point to what might be
causing the problem (line of code or commit)
**If you get help, help others. Good karma rulez!**
### Submitting a Pull Request
Before you submit your pull request consider the following guidelines:
* Search [GitHub](https://github.com/silkimen/cordova-plugin-advanced-http/pulls) for an open or
closed Pull Request that relates to your submission. You don't want to duplicate effort.
* Make your changes in a new git branch:
```shell
git checkout -b my-fix-branch master
```
* Create your patch
* Commit your changes using a descriptive commit message
* Push your branch to GitHub:
```shell
git push origin my-fix-branch
```
In GitHub, send a pull request to `cordova-plugin-advanced-http:master`.
If we suggest changes or the [CI build fails](#cibuild), then:
* Make the required updates.
* Commit your changes to your branch (e.g. `my-fix-branch`).
* Push the changes to your GitHub repository (this will update your Pull Request).
That's it! Thank you for your contribution!
### <a name="cibuild"></a> Pull Request Feedback
You can always check the results of the latest CI builds on
[Travis CI](https://travis-ci.org/silkimen/cordova-plugin-advanced-http/).
You can use this information to inspect failing tests in your PR.
## Attribution
This document is adapted from
[AngularJS' Contribution Guidelines](https://github.com/angular/angular.js/blob/master/CONTRIBUTING.md)
+149 -86
View File
@@ -24,9 +24,11 @@ Please check [CHANGELOG.md](CHANGELOG.md) for details about updating to a new ve
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
```shell
phonegap plugin add cordova-plugin-advanced-http
cordova plugin add cordova-plugin-advanced-http
cordova plugin add cordova-plugin-advanced-http
```
## Usage
@@ -38,7 +40,9 @@ This plugin registers a global object located at `cordova.plugin.http`.
This plugin creates a cordovaHTTP service inside of a cordovaHTTP module. You must load the module when you create your app's module.
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'cordovaHTTP']);
```js
var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'cordovaHTTP']);
```
You can then inject the cordovaHTTP service into your controllers. The functions can then be used identically to the examples shown below except that instead of accepting success and failure callback functions, each function returns a promise. For more information on promises in AngularJS read the [AngularJS docs](http://docs.angularjs.org/api/ng/service/$q). For more info on promises in general check out this article on [html5rocks](http://www.html5rocks.com/en/tutorials/es6/promises/). Make sure that you load cordova.js or phonegap.js after AngularJS is loaded.
@@ -48,27 +52,54 @@ You can then inject the cordovaHTTP service into your controllers. The function
### getBasicAuthHeader
This returns an object representing a basic HTTP Authorization header of the form `{'Authorization': 'Basic base64encodedusernameandpassword'}`
var header = cordovaHTTP.getBasicAuthHeader("user", "password");
```js
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.
cordovaHTTP.useBasicAuth("user", "password");
```js
cordova.plugin.http.useBasicAuth('user', 'password');
```
### setHeader
Set a header for all future requests. Takes a header and a value.
Set a header for all future requests to a specified host. Takes a hostname, a header and a value.
cordovaHTTP.setHeader("Header", "Value");
```js
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.
```js
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`.
```js
// 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');
```
### disableRedirect
If set to `true`, it won't follow redirects automatically. This is a global setting.
cordovaHTTP.disableRedirect(true);
```js
cordova.plugin.http.disableRedirect(true);
```
### setDataSerializer
Set the data serializer which will be used for all future POST and PUT requests. Takes a string representing the name of the serializer.
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.
cordovaHTTP.setDataSerializer("urlencoded");
```js
cordova.plugin.http.setDataSerializer('urlencoded');
```
You can choose one of these two:
* `urlencoded`: send data as url encoded content in body (content type "application/x-www-form-urlencoded")
@@ -79,12 +110,16 @@ Caution: `urlencoded` does not support serializing deep structures whereas `json
### setRequestTimeout
Set how long to wait for a request to respond, in seconds.
cordovaHTTP.setRequestTimeout(5.0);
```js
cordova.plugin.http.setRequestTimeout(5.0);
```
### clearCookies
Clear the cookie store.
cordovaHTTP.clearCookies();
```js
cordova.plugin.http.clearCookies();
```
## Asynchronous Functions
These functions all take success and error callbacks as their last 2 arguments.
@@ -96,20 +131,24 @@ To use SSL pinning you must include at least one .cer SSL certificate in your ap
As an alternative, you can store your .cer files in the www/certificates folder.
cordovaHTTP.enableSSLPinning(true, function() {
console.log('success!');
}, function() {
console.log('error :(');
});
```js
cordova.plugin.http.enableSSLPinning(true, function() {
console.log('success!');
}, function() {
console.log('error :(');
});
```
### acceptAllCerts
Accept all SSL certificates. Or disable accepting all certificates. This defaults to false.
cordovaHTTP.acceptAllCerts(true, function() {
console.log('success!');
}, function() {
console.log('error :(');
});
```js
cordova.plugin.http.acceptAllCerts(true, function() {
console.log('success!');
}, function() {
console.log('error :(');
});
```
### validateDomainName
This function was removed in v1.6.2. Domain name validation is disabled automatically when you enable "acceptAllCerts".
@@ -117,72 +156,88 @@ This function was removed in v1.6.2. Domain name validation is disabled automati
### removeCookies
Remove all cookies associated with a given URL.
cordovaHTTP.removeCookies(url);
```js
cordova.plugin.http.removeCookies(url);
```
### post<a name="post"></a>
Execute a POST request. Takes a URL, data, and headers.
#### success
The success function receives a response object with 3 properties: status, data, and headers. Status is the HTTP response code. Data is the response from the server as a string. Headers is an object with the headers. Here's a quick example:
The success function receives a response object with 3 properties: status, data, and headers. **status** is the HTTP response code as numeric value. **data** is the response from the server 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.
{
status: 200,
data: "{'id': 12, 'message': 'test'}",
headers: {
"Content-Length": "247"
}
}
Here's a quick example:
```js
{
status: 200,
data: '{"id": 12, "message": "test"}',
headers: {
'content-length': '247'
}
}
```
Most apis will return JSON meaning you'll want to parse the data like in the example below:
cordovaHTTP.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);
});
```js
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 3 properties: status, error and headers. Status is the HTTP response code. Error is the error response from the server as a string. Headers is an object with the headers. Here's a quick example:
The error function receives a response object with 3 properties: status, error and headers. **status** is the HTTP response code as numeric value. **error** is the error response from the server 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.
{
status: 403,
error: "Permission denied",
headers: {
"Content-Length": "247"
}
}
Here's a quick example:
```js
{
status: 403,
error: 'Permission denied',
headers: {
'content-length': '247'
}
}
```
### get
Execute a GET request. Takes a URL, parameters, and headers. See the [post](#post) documentation for details on what is returned on success and failure.
cordovaHTTP.get("https://google.com/", {
id: 12,
message: "test"
}, { Authorization: "OAuth2: token" }, function(response) {
console.log(response.status);
}, function(response) {
console.error(response.error);
});
```js
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](#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](#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](#post) documentation for details on what is returned on success and failure.
@@ -192,30 +247,34 @@ Execute a HEAD request. Takes a URL, parameters, and headers. See the [post](#
### uploadFile
Uploads a file saved on the device. Takes a URL, parameters, headers, filePath, and the name of the parameter to pass the file along as. See the [post](#post) documentation for details on what is returned on success and failure.
cordovaHTTP.uploadFile("https://google.com/", {
id: 12,
message: "test"
}, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", "picture", function(response) {
console.log(response.status);
}, function(response) {
console.error(response.error);
});
```js
cordova.plugin.http.uploadFile("https://google.com/", {
id: 12,
message: 'test'
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', 'picture', 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](#post) documentation for details on what is returned on failure. On success this function returns a cordova [FileEntry object](http://cordova.apache.org/docs/en/3.3.0/cordova_file_file.md.html#FileEntry).
cordovaHTTP.downloadFile("https://google.com/", {
id: 12,
message: "test"
}, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", function(entry) {
// prints the filename
console.log(entry.name);
```js
cordova.plugin.http.downloadFile("https://google.com/", {
id: 12,
message: 'test'
}, { Authorization: 'OAuth2: token' }, 'file:///somepicture.jpg', function(entry) {
// prints the filename
console.log(entry.name);
// prints the filePath
console.log(entry.fullPath);
}, function(response) {
console.error(response.error);
});
// prints the filePath
console.log(entry.fullPath);
}, function(response) {
console.error(response.error);
});
```
## Libraries
@@ -226,3 +285,7 @@ This plugin utilizes some awesome open source networking libraries. These are bo
- Android - [http-request](https://github.com/kevinsawicki/http-request)
We made a few modifications to both of them.
## Contribute & Develop
We've set up a separate document for our [contribution guidelines](CONTRIBUTING.md).
+5 -2
View File
@@ -1,9 +1,11 @@
{
"name": "cordova-plugin-advanced-http",
"version": "1.6.2",
"version": "1.7.1",
"description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
"scripts": {
"test": "./scripts/build-test-app.sh && ./scripts/test.sh --ios --emulator",
"testapp": "./scripts/build-test-app.sh && ./scripts/test-app.sh --ios --emulator",
"testjs": "mocha ./test/js-mocha-specs.js",
"test": "npm run testjs && npm run testapp",
"release": "npm run test && ./scripts/release.sh"
},
"cordova": {
@@ -55,6 +57,7 @@
"colors": "1.1.2",
"cordova": "7.0.1",
"mocha": "4.0.0",
"mock-require": "2.0.2",
"mz": "2.7.0",
"umd-tough-cookie": "2.3.2",
"wd": "1.4.1",
+1 -1
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="1.6.2">
<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="1.7.1">
<name>Advanced HTTP plugin</name>
<description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
+1 -1
View File
@@ -9,7 +9,7 @@ CDV=$ROOT/node_modules/.bin/cordova
rm -rf $ROOT/temp
mkdir $ROOT/temp
cp -r $ROOT/test/app-template/ $ROOT/temp/
cp $ROOT/test/test-definitions.js $ROOT/temp/www/js/
cp $ROOT/test/app-test-definitions.js $ROOT/temp/www/
cd $ROOT/temp
$CDV prepare
$CDV plugins add $ROOT
+1 -1
View File
@@ -4,5 +4,5 @@ set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
pushd $ROOT
./node_modules/.bin/mocha ./test/mocha-specs/test.js "$@"
./node_modules/.bin/mocha ./test/app-mocha-specs/test.js "$@"
popd
@@ -28,13 +28,13 @@ abstract class CordovaHttp {
private static AtomicBoolean disableRedirect = new AtomicBoolean(false);
private String urlString;
private JSONObject params;
private Object params;
private String serializerName;
private JSONObject headers;
private int timeoutInMilliseconds;
private CallbackContext callbackContext;
public CordovaHttp(String urlString, JSONObject params, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttp(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.serializerName = "default";
@@ -43,7 +43,7 @@ abstract class CordovaHttp {
this.callbackContext = callbackContext;
}
public CordovaHttp(String urlString, JSONObject params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttp(String urlString, Object params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.serializerName = serializerName;
@@ -78,7 +78,7 @@ abstract class CordovaHttp {
return this.urlString;
}
protected JSONObject getParamsObject() {
protected Object getParamsObject() {
return this.params;
}
@@ -86,8 +86,12 @@ abstract class CordovaHttp {
return this.serializerName;
}
protected HashMap<String, Object> getParamsMap() throws JSONException {
return this.getMapFromJSONObject(this.params);
protected HashMap<String, Object> getParamsMap() throws JSONException, Exception {
if (this.params instanceof JSONObject) {
return this.getMapFromJSONObject((JSONObject) this.params);
} else {
throw new Exception("unsupported params type, needs to be a JSON object");
}
}
protected JSONObject getHeadersObject() {
@@ -150,7 +154,7 @@ abstract class CordovaHttp {
List<String> value = entry.getValue();
if ((key != null) && (!value.isEmpty())) {
filteredHeaders.put(key, TextUtils.join(", ", value));
filteredHeaders.put(key.toLowerCase(), TextUtils.join(", ", value));
}
}
@@ -17,7 +17,7 @@ import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpDelete extends CordovaHttp implements Runnable {
public CordovaHttpDelete(String urlString, JSONObject data, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttpDelete(String urlString, Object data, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, data, headers, timeout, callbackContext);
}
@@ -59,6 +59,8 @@ class CordovaHttpDelete extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -23,7 +23,7 @@ import org.json.JSONObject;
class CordovaHttpDownload extends CordovaHttp implements Runnable {
private String filePath;
public CordovaHttpDownload(String urlString, JSONObject params, JSONObject headers, String filePath, int timeout, CallbackContext callbackContext) {
public CordovaHttpDownload(String urlString, Object params, JSONObject headers, String filePath, int timeout, CallbackContext callbackContext) {
super(urlString, params, headers, timeout, callbackContext);
this.filePath = filePath;
}
@@ -69,6 +69,8 @@ class CordovaHttpDownload extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -17,7 +17,7 @@ import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpGet extends CordovaHttp implements Runnable {
public CordovaHttpGet(String urlString, JSONObject params, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttpGet(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, headers, timeout, callbackContext);
}
@@ -59,6 +59,8 @@ class CordovaHttpGet extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -16,7 +16,7 @@ import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpHead extends CordovaHttp implements Runnable {
public CordovaHttpHead(String urlString, JSONObject params, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttpHead(String urlString, Object params, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, headers, timeout, callbackContext);
}
@@ -58,6 +58,8 @@ class CordovaHttpHead extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -16,7 +16,7 @@ import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpPatch extends CordovaHttp implements Runnable {
public CordovaHttpPatch(String urlString, JSONObject params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttpPatch(String urlString, Object params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, serializerName, headers, timeout, callbackContext);
}
@@ -65,6 +65,8 @@ class CordovaHttpPatch extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -36,7 +36,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("post")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
int timeoutInMilliseconds = args.getInt(4) * 1000;
@@ -45,7 +45,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
cordova.getThreadPool().execute(post);
} else if (action.equals("get")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
JSONObject headers = args.getJSONObject(2);
int timeoutInMilliseconds = args.getInt(3) * 1000;
CordovaHttpGet get = new CordovaHttpGet(urlString, params, headers, timeoutInMilliseconds, callbackContext);
@@ -53,7 +53,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
cordova.getThreadPool().execute(get);
} else if (action.equals("put")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
int timeoutInMilliseconds = args.getInt(4) * 1000;
@@ -62,7 +62,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
cordova.getThreadPool().execute(put);
} else if (action.equals("patch")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
int timeoutInMilliseconds = args.getInt(4) * 1000;
@@ -72,7 +72,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
}
else if (action.equals("delete")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
JSONObject headers = args.getJSONObject(2);
int timeoutInMilliseconds = args.getInt(3) * 1000;
CordovaHttpDelete delete = new CordovaHttpDelete(urlString, params, headers, timeoutInMilliseconds, callbackContext);
@@ -80,7 +80,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
cordova.getThreadPool().execute(delete);
} else if (action.equals("head")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
JSONObject headers = args.getJSONObject(2);
int timeoutInMilliseconds = args.getInt(3) * 1000;
CordovaHttpHead head = new CordovaHttpHead(urlString, params, headers, timeoutInMilliseconds, callbackContext);
@@ -103,7 +103,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
callbackContext.success();
} else if (action.equals("uploadFile")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
JSONObject headers = args.getJSONObject(2);
String filePath = args.getString(3);
String name = args.getString(4);
@@ -113,7 +113,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
cordova.getThreadPool().execute(upload);
} else if (action.equals("downloadFile")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
Object params = args.get(1);
JSONObject headers = args.getJSONObject(2);
String filePath = args.getString(3);
int timeoutInMilliseconds = args.getInt(4) * 1000;
@@ -16,7 +16,7 @@ import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpPost extends CordovaHttp implements Runnable {
public CordovaHttpPost(String urlString, JSONObject params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttpPost(String urlString, Object params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, params, serializerName, headers, timeout, callbackContext);
}
@@ -65,6 +65,8 @@ class CordovaHttpPost extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -16,7 +16,7 @@ import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
class CordovaHttpPut extends CordovaHttp implements Runnable {
public CordovaHttpPut(String urlString, JSONObject data, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
public CordovaHttpPut(String urlString, Object data, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
super(urlString, data, serializerName, headers, timeout, callbackContext);
}
@@ -55,7 +55,7 @@ class CordovaHttpPut extends CordovaHttp implements Runnable {
}
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
@@ -65,6 +65,8 @@ class CordovaHttpPut extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -30,7 +30,7 @@ class CordovaHttpUpload extends CordovaHttp implements Runnable {
private String filePath;
private String name;
public CordovaHttpUpload(String urlString, JSONObject params, JSONObject headers, String filePath, String name, int timeout, CallbackContext callbackContext) {
public CordovaHttpUpload(String urlString, Object params, JSONObject headers, String filePath, String name, int timeout, CallbackContext callbackContext) {
super(urlString, params, headers, timeout, callbackContext);
this.filePath = filePath;
this.name = name;
@@ -97,7 +97,7 @@ class CordovaHttpUpload extends CordovaHttp implements Runnable {
this.respondWithError("There was an error loading the file");
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
@@ -107,6 +107,8 @@ class CordovaHttpUpload extends CordovaHttp implements Runnable {
} else {
this.respondWithError("There was an error with the request");
}
} catch (Exception e) {
this.respondWithError(-1, e.getMessage());
}
}
}
@@ -4,11 +4,11 @@ const wd = require('wd');
const apps = require('./helpers/apps');
const caps = Object.assign({}, require('./helpers/caps'));
const serverConfig = require('./helpers/server');
const testDefinitions = require('../test-definitions');
const testDefinitions = require('../app-test-definitions');
const pkgjson = require('../../package.json');
describe('Advanced HTTP', function() {
let driver;
let driver = null;
let allPassed = true;
this.timeout(900000);
@@ -37,10 +37,27 @@ describe('Advanced HTTP', function() {
.then(text => text.match(/\d+:\ (.*)/)[1])
.should.eventually.become(testTitle, 'Test description is not matching!');
const validateResult = text => driver
.elementById('resultTextarea')
.getAttribute('value')
.should.eventually.include(text);
const waitToBeFinished = timeout => new Promise((resolve, reject) => {
const timeoutTimestamp = Date.now() + timeout;
const checkIfFinished = () => driver
.elementById('statusInput')
.getValue()
.then(value => {
if (value === 'finished') {
resolve();
} else if (Date.now() > timeoutTimestamp) {
reject('Test function timed out!');
} else {
setTimeout(checkIfFinished, 500);
}
});
checkIfFinished();
});
const validateResult = testDefinition => driver
.safeExecute('app.lastResult')
.then(result => testDefinition.validationFunc(driver, result));
const clickNext = () => driver
.elementById('nextBtn')
@@ -67,7 +84,8 @@ describe('Advanced HTTP', function() {
return clickNext()
.then(() => validateTestIndex(index))
.then(() => validateTestTitle(this.test.title))
.then(() => validateResult(definition.expected))
.then(() => waitToBeFinished(definition.timeout || 10000))
.then(() => validateResult(definition))
});
});
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

@@ -15,9 +15,19 @@ body {
button, input, textarea {
display: block;
box-sizing: border-box;
width: 100%;
}
button {
height: 2.5em;
font-size: 10pt;
}
input {
text-align: center;
}
h1 {
font-size: 12pt;
text-align: center;
+6 -5
View File
@@ -5,16 +5,17 @@
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<h1 id="descriptionLbl">Advanced HTTP test suite</h1>
<textarea rows="16" cols="50" id="expectedTextarea">Click next to run first test.</textarea>
<textarea rows="16" cols="50" id="resultTextarea"></textarea>
<input value="idle" id="statusInput" readonly></input>
<textarea rows="16" cols="50" id="expectedTextarea" readonly>Click next to run first test.</textarea>
<textarea rows="16" cols="50" id="resultTextarea" readonly></textarea>
<button id="nextBtn">Run next test</button>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/test-definitions.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="app-test-definitions.js"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
@@ -1,6 +1,8 @@
const app = {
testIndex: -1,
lastResult: null,
initialize: function() {
document.getElementById('nextBtn').addEventListener('click', app.onNextBtnClick);
},
@@ -12,11 +14,27 @@ const app = {
},
reject: function(content) {
document.getElementById('statusInput').value = 'finished';
app.printResult('result - rejected', content);
app.lastResult = {
type: 'rejected',
data: content
};
},
resolve: function(content) {
document.getElementById('statusInput').value = 'finished';
app.printResult('result - resolved', content);
app.lastResult = {
type: 'resolved',
data: content
};
},
getResult: function(cb) {
cb(app.lastResult);
},
runTest: function(index) {
@@ -24,6 +42,7 @@ const app = {
const titleText = app.testIndex + ': ' + testDefinition.description;
const expectedText = 'expected - ' + testDefinition.expected;
document.getElementById('statusInput').value = 'running';
document.getElementById('expectedTextarea').value = expectedText;
document.getElementById('resultTextarea').value = '';
document.getElementById('descriptionLbl').innerText = titleText;
@@ -31,6 +50,8 @@ const app = {
},
onBeforeTest: function(testIndex, cb) {
app.lastResult = null;
if (hooks && hooks.onBeforeEachTest) {
return hooks.onBeforeEachTest(function() {
const testDefinition = tests[testIndex];
+166
View File
@@ -0,0 +1,166 @@
const hooks = {
onBeforeEachTest: function(done) {
cordova.plugin.http.acceptAllCerts(false, done, done);
}
};
const helpers = {
acceptAllCerts: function(done) { cordova.plugin.http.acceptAllCerts(true, done, done); },
setJsonSerializer: function(done) { done(cordova.plugin.http.setDataSerializer('json')); }
};
const tests = [
{
description: 'should reject self signed cert (GET)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.get('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error:'cancelled' });
}
},{
description: 'should reject self signed cert (PUT)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.put('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error:'cancelled' });
}
},{
description: 'should reject self signed cert (POST)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.post('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error:'cancelled' });
}
},{
description: 'should reject self signed cert (PATCH)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.patch('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error:'cancelled' });
}
},{
description: 'should reject self signed cert (DELETE)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.delete('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.be.eql({ status: -1, error:'cancelled' });
}
},{
description: 'should accept bad cert (GET)',
expected: 'resolved: {"status":200, ...',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.get('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
result.data.should.include({ status: 200 });
}
},{
description: 'should accept bad cert (PUT)',
expected: 'rejected: {"status":405, ... // will be rejected because PUT is not allowed',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.put('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.include({ status: 405 });
}
},{
description: 'should accept bad cert (POST)',
expected: 'rejected: {"status":405, ... // will be rejected because POST is not allowed',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.post('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.include({ status: 405 });
}
},{
description: 'should accept bad cert (PATCH)',
expected: 'rejected: {"status":405, ... // will be rejected because PATCH is not allowed',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.patch('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.include({ status: 405 });
}
},{
description: 'should accept bad cert (DELETE)',
expected: 'rejected: {"status":405, ... // will be rejected because DELETE is not allowed',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.delete('https://self-signed.badssl.com/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('rejected');
result.data.should.include({ status: 405 });
}
},{
description: 'should fetch data from http://httpbin.org/ (GET)',
expected: 'resolved: {"status":200, ...',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.get('http://httpbin.org/', {}, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
result.data.should.include({ status: 200 });
}
},{
description: 'should send JSON object correctly (POST)',
expected: 'resolved: {"status": 200, data: "{\\"json\\":\\"test\\": \\"testString\\"}\" ...',
before: helpers.setJsonSerializer,
func: function(resolve, reject) { cordova.plugin.http.post('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
JSON.parse(result.data.data).json.should.eql({ test: 'testString' });
}
},{
description: 'should send JSON object correctly (PUT)',
expected: 'resolved: {"status": 200, data: "{\\"json\\":\\"test\\": \\"testString\\"}\" ...',
before: helpers.setJsonSerializer,
func: function(resolve, reject) { cordova.plugin.http.put('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
JSON.parse(result.data.data).json.should.eql({ test: 'testString' });
}
},{
description: 'should send JSON object correctly (PATCH)',
expected: 'resolved: {"status": 200, data: "{\\"json\\":\\"test\\": \\"testString\\"}\" ...',
before: helpers.setJsonSerializer,
func: function(resolve, reject) { cordova.plugin.http.patch('http://httpbin.org/anything', { test: 'testString' }, {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
JSON.parse(result.data.data).json.should.eql({ test: 'testString' });
}
},{
description: 'should send JSON array correctly (POST)',
expected: 'resolved: {"status": 200, data: "[ 1, 2, 3 ]\" ...',
before: helpers.setJsonSerializer,
func: function(resolve, reject) { cordova.plugin.http.post('http://httpbin.org/anything', [ 1, 2, 3 ], {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
JSON.parse(result.data.data).json.should.eql([ 1, 2, 3 ]);
}
},{
description: 'should send JSON array correctly (PUT)',
expected: 'resolved: {"status": 200, data: "[ 1, 2, 3 ]\" ...',
before: helpers.setJsonSerializer,
func: function(resolve, reject) { cordova.plugin.http.put('http://httpbin.org/anything', [ 1, 2, 3 ], {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
JSON.parse(result.data.data).json.should.eql([ 1, 2, 3 ]);
}
},{
description: 'should send JSON array correctly (PATCH)',
expected: 'resolved: {"status": 200, data: "[ 1, 2, 3 ]\" ...',
before: helpers.setJsonSerializer,
func: function(resolve, reject) { cordova.plugin.http.patch('http://httpbin.org/anything', [ 1, 2, 3 ], {}, resolve, reject); },
validationFunc: function(driver, result) {
result.type.should.be.equal('resolved');
JSON.parse(result.data.data).json.should.eql([ 1, 2, 3 ]);
}
}
];
if (typeof module !== 'undefined' && module.exports) {
module.exports = { tests: tests, hooks: hooks };
}
+121
View File
@@ -0,0 +1,121 @@
const chai = require('chai');
const mock = require('mock-require');
const path = require('path');
const should = chai.should();
const PLUGIN_ID = path.resolve(__dirname, '..', 'www', 'advanced-http');
describe('Advanced HTTP www interface', function() {
let http = {};
const noop = () => { /* intentionally doing nothing */ };
const loadHttp = () => {
http = mock.reRequire('../www/advanced-http');
};
this.timeout(900000);
beforeEach(() => {
// mocked btoa function (base 64 encoding strings)
global.btoa = decoded => new Buffer(decoded).toString('base64');
mock('cordova/exec', noop);
mock(`${PLUGIN_ID}.angular-integration`, { registerService: noop });
mock(`${PLUGIN_ID}.cookie-handler`, {});
loadHttp();
});
it('sets global headers correctly with two args (old interface)', () => {
http.setHeader('myKey', 'myValue');
http.headers['*'].myKey.should.equal('myValue');
});
it('sets global headers correctly with three args (new interface)', () => {
http.setHeader('*', 'myKey', 'myValue');
http.headers['*'].myKey.should.equal('myValue');
});
it('sets host headers correctly', () => {
http.setHeader('www.google.de', 'myKey', 'myValue');
http.headers['www.google.de'].myKey.should.equal('myValue');
});
it('resolves global headers correctly', () => {
mock(`${PLUGIN_ID}.cookie-handler`, {
getCookieString: () => 'fakeCookieString'
});
mock('cordova/exec', (onSuccess, onFail, namespace, method, params) => {
const headers = params[2];
headers.should.eql({
Cookie: 'fakeCookieString',
myKey: 'myValue'
});
});
loadHttp();
http.setHeader('*', 'myKey', 'myValue');
http.get('url', {}, {}, noop, noop);
});
it('resolves host headers correctly (set without port number)', () => {
mock(`${PLUGIN_ID}.cookie-handler`, {
getCookieString: () => 'fakeCookieString'
});
mock('cordova/exec', (onSuccess, onFail, namespace, method, params) => {
const headers = params[2];
headers.should.eql({
Cookie: 'fakeCookieString',
myKey: 'myValue'
});
});
loadHttp();
http.setHeader('www.google.de', 'myKey', 'myValue');
http.get('https://www.google.de/?gws_rd=ssl', {}, {}, noop, noop);
});
it('resolves host headers correctly (set with port number)', () => {
mock(`${PLUGIN_ID}.cookie-handler`, {
getCookieString: () => 'fakeCookieString'
});
mock('cordova/exec', (onSuccess, onFail, namespace, method, params) => {
const headers = params[2];
headers.should.eql({
Cookie: 'fakeCookieString',
myKey: 'myValue'
});
});
loadHttp();
http.setHeader('www.google.de:8080', 'myKey', 'myValue');
http.get('https://www.google.de:8080/?gws_rd=ssl', {}, {}, noop, noop);
});
it('resolves request headers correctly', () => {
mock(`${PLUGIN_ID}.cookie-handler`, {
getCookieString: () => 'fakeCookieString'
});
mock('cordova/exec', (onSuccess, onFail, namespace, method, params) => {
const headers = params[2];
headers.should.eql({
Cookie: 'fakeCookieString',
myKey: 'myValue'
});
});
loadHttp();
http.get('https://www.google.de/?gws_rd=ssl', {}, { myKey: 'myValue' }, noop, noop);
});
it('sets basic authentication header correctly', () => {
http.useBasicAuth('name', 'pass');
http.headers['*'].Authorization.should.equal('Basic bmFtZTpwYXNz');
});
});
-67
View File
@@ -1,67 +0,0 @@
const hooks = {
onBeforeEachTest: function(done) {
cordova.plugin.http.acceptAllCerts(false, done, done);
}
};
const helpers = {
acceptAllCerts: function(done) { cordova.plugin.http.acceptAllCerts(true, done, done); }
};
const tests = [
{
description: 'should reject self signed cert (GET)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.get('https://self-signed.badssl.com/', {}, {}, resolve, reject); }
},{
description: 'should reject self signed cert (PUT)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.put('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); }
},{
description: 'should reject self signed cert (POST)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.post('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); }
},{
description: 'should reject self signed cert (PATCH)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.patch('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); }
},{
description: 'should reject self signed cert (DELETE)',
expected: 'rejected: {"status":-1,"error":"cancelled"}',
func: function(resolve, reject) { cordova.plugin.http.delete('https://self-signed.badssl.com/', {}, {}, resolve, reject); }
},{
description: 'should accept bad cert (GET)',
expected: 'resolved: {\"status\":200,',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.get('https://self-signed.badssl.com/', {}, {}, resolve, reject); }
},{
description: 'should accept bad cert (PUT)',
expected: 'rejected: {\"status\":405,', // will be rejected because PUT is not allowed
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.put('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); }
},{
description: 'should accept bad cert (POST)',
expected: 'rejected: {\"status\":405,', // will be rejected because POST is not allowed
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.post('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); }
},{
description: 'should accept bad cert (PATCH)',
expected: 'rejected: {\"status\":405,', // will be rejected because PATCH is not allowed
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.patch('https://self-signed.badssl.com/', { test: 'testString' }, {}, resolve, reject); }
},{
description: 'should accept bad cert (DELETE)',
expected: 'rejected: {\"status\":405,', // will be rejected because DELETE is not allowed
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.delete('https://self-signed.badssl.com/', {}, {}, resolve, reject); }
},{
description: 'should fetch data from http://google.com/ (GET)',
expected: 'resolved: {\"status\":200,',
before: helpers.acceptAllCerts,
func: function(resolve, reject) { cordova.plugin.http.get('http://google.com/', {}, {}, resolve, reject); }
}
];
if (module && module.exports) {
module.exports = { tests: tests, hooks: hooks };
}
+41 -27
View File
@@ -114,6 +114,24 @@ function getCookieHeader(url) {
return { Cookie: cookieHandler.getCookieString(url) };
}
function getMatchingHostHeaders(url, headersList) {
var matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
var domain = matches && matches[1];
return headersList[domain] || null;
}
function getMergedHeaders(url, requestHeaders, predefinedHeaders) {
var globalHeaders = predefinedHeaders['*'] || {};
var hostHeaders = getMatchingHostHeaders(url, predefinedHeaders) || {};
var mergedHeaders = mergeHeaders(globalHeaders, hostHeaders);
mergedHeaders = mergeHeaders(mergedHeaders, requestHeaders);
mergedHeaders = mergeHeaders(mergedHeaders, getCookieHeader(url));
return mergedHeaders;
}
function handleMissingCallbacks(successFn, failFn) {
if (Object.prototype.toString.call(successFn) !== '[object Function]') {
throw new Error('advanced-http: missing mandatory "onSuccess" callback function');
@@ -133,10 +151,22 @@ var http = {
return {'Authorization': 'Basic ' + b64EncodeUnicode(username + ':' + password)};
},
useBasicAuth: function (username, password) {
this.headers.Authorization = 'Basic ' + b64EncodeUnicode(username + ':' + password);
this.setHeader('*', 'Authorization', 'Basic ' + b64EncodeUnicode(username + ':' + password));
},
setHeader: function (header, value) {
this.headers[header] = value;
setHeader: function () {
// this one is for being backward compatible
var host = '*';
var header = arguments[0];
var value = arguments[1];
if (arguments.length === 3) {
host = arguments[0];
header = arguments[1];
value = arguments[2];
}
this.headers[host] = this.headers[host] || {};
this.headers[host][header] = value;
},
setDataSerializer: function (serializer) {
this.dataSerializer = checkSerializer(serializer);
@@ -166,9 +196,7 @@ var http = {
handleMissingCallbacks(success, failure);
data = data || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
@@ -179,9 +207,7 @@ var http = {
handleMissingCallbacks(success, failure);
params = params || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
@@ -192,9 +218,7 @@ var http = {
handleMissingCallbacks(success, failure);
data = data || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
@@ -206,9 +230,7 @@ var http = {
handleMissingCallbacks(success, failure);
data = data || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
@@ -220,9 +242,7 @@ var http = {
handleMissingCallbacks(success, failure);
params = params || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
@@ -233,9 +253,7 @@ var http = {
handleMissingCallbacks(success, failure);
params = params || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
@@ -246,9 +264,7 @@ var http = {
handleMissingCallbacks(success, failure);
params = params || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
@@ -259,9 +275,7 @@ var http = {
handleMissingCallbacks(success, failure);
params = params || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
headers = getMergedHeaders(url, headers, this.headers);
var onSuccess = injectCookieHandler(url, injectFileEntryHandler(success));
var onFail = injectCookieHandler(url, failure);
+2 -2
View File
@@ -38,8 +38,8 @@ function registerService(http) {
useBasicAuth: function (username, password) {
return http.useBasicAuth(username, password);
},
setHeader: function (header, value) {
return http.setHeader(header, value);
setHeader: function (host, header, value) {
return http.setHeader(host, header, value);
},
setDataSerializer: function (serializer) {
return http.setDataSerializer(serializer);