Compare commits

...
13 Commits
20 changed files with 723 additions and 476 deletions
+9 -1
View File
@@ -1,5 +1,13 @@
# Changelog # Changelog
## v1.4.0
- forked from "cordova-plugin-http" v1.2.0 (see https://github.com/wymsee/cordova-HTTP)
- added configuration for data serializer
- added HTTP methods PUT and DELETE
# Previous changelog (cordova-plugin-http)
## v1.2.0 ## v1.2.0
- Added support for TLSv1.1 and TLSv1.2 for android versions 4.1-4.4 (API levels 16-19) - Added support for TLSv1.1 and TLSv1.2 for android versions 4.1-4.4 (API levels 16-19)
@@ -72,4 +80,4 @@
- Reports SSL Handshake errors rather than giving a generic error (Thanks to devgeeks) - Reports SSL Handshake errors rather than giving a generic error (Thanks to devgeeks)
- Exporting http as a module (Thanks to pvsaikrishna) - Exporting http as a module (Thanks to pvsaikrishna)
- Added Limitations section to readme (Thanks to cvillerm) - Added Limitations section to readme (Thanks to cvillerm)
- Fixed examples (Thanks to hideov) - Fixed examples (Thanks to hideov)
+46 -27
View File
@@ -1,11 +1,13 @@
cordovaHTTP Cordova Advanced HTTP
================== =====================
Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS and Android. Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS and Android.
This is a fork of [Wymsee's Cordova-HTTP plugin](https://github.com/wymsee/cordova-HTTP).
## Advantages over Javascript requests ## Advantages over Javascript requests
- Background threading - all requests are done in a background thread. - Background threading - all requests are done in a background thread.
- Handling of HTTP code 401 - read more at [Issue CB-2415](https://issues.apache.org/jira/browse/CB-2415).
- SSL Pinning - read more at [LumberBlog](http://blog.lumberlabs.com/2012/04/why-app-developers-should-care-about.html). - SSL Pinning - read more at [LumberBlog](http://blog.lumberlabs.com/2012/04/why-app-developers-should-care-about.html).
## Updates ## Updates
@@ -17,26 +19,26 @@ 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 The plugin conforms to the Cordova plugin specification, it can be installed
using the Cordova / Phonegap command line interface. using the Cordova / Phonegap command line interface.
phonegap plugin add cordova-plugin-http phonegap plugin add cordova-plugin-advanced-http
cordova plugin add cordova-plugin-http cordova plugin add cordova-plugin-advanced-http
## Usage ## Usage
### AngularJS ### Without AngularJS
This plugin registers a global object located at `cordova.plugin.http`.
### With AngularJS
This plugin creates a cordovaHTTP service inside of a cordovaHTTP module. You must load the module when you create your app's module. 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']); 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. 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.
### Not AngularJS
This plugin registers a `cordovaHTTP` global on window ## Synchronous Functions
## Sync Functions
### getBasicAuthHeader ### getBasicAuthHeader
This returns an object representing a basic HTTP Authorization header of the form `{'Authorization': 'Basic base64encodedusernameandpassword'}` This returns an object representing a basic HTTP Authorization header of the form `{'Authorization': 'Basic base64encodedusernameandpassword'}`
@@ -47,14 +49,25 @@ This returns an object representing a basic HTTP Authorization header of the for
This sets up all future requests to use Basic HTTP authentication with the given username and password. This sets up all future requests to use Basic HTTP authentication with the given username and password.
cordovaHTTP.useBasicAuth("user", "password"); cordovaHTTP.useBasicAuth("user", "password");
### setHeader ### setHeader
Set a header for all future requests. Takes a header and a value. Set a header for all future requests. Takes a header and a value.
cordovaHTTP.setHeader("Header", "Value"); cordovaHTTP.setHeader("Header", "Value");
## Async Functions ### 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.
cordovaHTTP.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")
* `json`: send data as JSON encoded content in body (content type "application/json")
Caution: `urlencoded` does not support serializing deep structures whereas `json` does.
## Asynchronous Functions
These functions all take success and error callbacks as their last 2 arguments. These functions all take success and error callbacks as their last 2 arguments.
### enableSSLPinning ### enableSSLPinning
@@ -69,7 +82,7 @@ As an alternative, you can store your .cer files in the www/certificates folder.
}, function() { }, function() {
console.log('error :('); console.log('error :(');
}); });
### acceptAllCerts ### acceptAllCerts
Accept all SSL certificates. Or disable accepting all certificates. This defaults to false. Accept all SSL certificates. Or disable accepting all certificates. This defaults to false.
@@ -78,7 +91,7 @@ Accept all SSL certificates. Or disable accepting all certificates. This defau
}, function() { }, function() {
console.log('error :('); console.log('error :(');
}); });
### validateDomainName ### validateDomainName
Whether or not to validate the domain name in the certificate. This defaults to true. Whether or not to validate the domain name in the certificate. This defaults to true.
@@ -87,9 +100,9 @@ Whether or not to validate the domain name in the certificate. This defaults to
}, function() { }, function() {
console.log('error :('); console.log('error :(');
}); });
### post<a name="post"></a> ### post<a name="post"></a>
Execute a POST request. Takes a URL, parameters, and headers. Execute a POST request. Takes a URL, data, and headers.
#### success #### 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. Data is the response from the server as a string. Headers is an object with the headers. Here's a quick example:
@@ -101,7 +114,7 @@ The success function receives a response object with 3 properties: status, data,
"Content-Length": "247" "Content-Length": "247"
} }
} }
Most apis will return JSON meaning you'll want to parse the data like in the example below: Most apis will return JSON meaning you'll want to parse the data like in the example below:
cordovaHTTP.post("https://google.com/", { cordovaHTTP.post("https://google.com/", {
@@ -120,12 +133,12 @@ Most apis will return JSON meaning you'll want to parse the data like in the exa
}, function(response) { }, function(response) {
// prints 403 // prints 403
console.log(response.status); console.log(response.status);
//prints Permission denied //prints Permission denied
console.log(response.error); console.log(response.error);
}); });
#### failure #### 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. Error is the error response from the server as a string. Headers is an object with the headers. Here's a quick example:
@@ -136,7 +149,7 @@ The error function receives a response object with 3 properties: status, error a
"Content-Length": "247" "Content-Length": "247"
} }
} }
### get ### 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. 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.
@@ -148,7 +161,13 @@ Execute a GET request. Takes a URL, parameters, and headers. See the [post](#p
}, function(response) { }, function(response) {
console.error(response.error); 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.
### 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.
### uploadFile ### 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. 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.
@@ -160,7 +179,7 @@ Uploads a file saved on the device. Takes a URL, parameters, headers, filePath,
}, function(response) { }, function(response) {
console.error(response.error); console.error(response.error);
}); });
### downloadFile ### 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). 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).
@@ -170,7 +189,7 @@ Downloads a file and saves it to the device. Takes a URL, parameters, headers,
}, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", function(entry) { }, { Authorization: "OAuth2: token" }, "file:///somepicture.jpg", function(entry) {
// prints the filename // prints the filename
console.log(entry.name); console.log(entry.name);
// prints the filePath // prints the filePath
console.log(entry.fullPath); console.log(entry.fullPath);
}, function(response) { }, function(response) {
+20 -7
View File
@@ -1,9 +1,9 @@
{ {
"name": "cordova-plugin-http", "name": "cordova-plugin-advanced-http",
"version": "1.2.0", "version": "1.4.0",
"description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning", "description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
"cordova": { "cordova": {
"id": "cordova-plugin-http", "id": "cordova-plugin-advanced-http",
"platforms": [ "platforms": [
"ios", "ios",
"android" "android"
@@ -11,14 +11,16 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/wymsee/cordova-HTTP.git" "url": "git+https://github.com/silkimen/cordova-plugin-advanced-http.git"
}, },
"keywords": [ "keywords": [
"cordova", "cordova",
"device", "device",
"ecosystem:cordova", "ecosystem:cordova",
"cordova-ios", "cordova-ios",
"cordova-android" "cordova-android",
"ssl",
"tls"
], ],
"engines": [ "engines": [
{ {
@@ -27,9 +29,20 @@
} }
], ],
"author": "Wymsee", "author": "Wymsee",
"contributors": [
"devgeeks",
"EddyVerbruggen",
"mbektchiev",
"denisbabineau",
"andrey-tsaplin",
"pvsaikrishna",
"cvillerm",
"hideov",
"Mobisys"
],
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://github.com/wymsee/cordova-HTTP/issues" "url": "https://github.com/silkimen/cordova-plugin-advanced-http/issues"
}, },
"homepage": "https://github.com/wymsee/cordova-HTTP#readme" "homepage": "https://github.com/silkimen/cordova-plugin-advanced-http#readme"
} }
+22 -20
View File
@@ -1,23 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0" <plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-http" id="cordova-plugin-advanced-http"
version="1.2.0"> version="1.4.0">
<name>Advanced HTTP plugin</name>
<name>SSL Pinning</name>
<description> <description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
</description> </description>
<engines> <engines>
<engine name="cordova" version=">=3.0.0" /> <engine name="cordova" version=">=3.5.0" />
</engines> </engines>
<dependency id="cordova-plugin-file" version=">=2.0.0" /> <dependency id="cordova-plugin-file" version=">=2.0.0" />
<js-module src="www/cordovaHTTP.js" name="CordovaHttpPlugin"> <js-module src="www/cordovaHttp.js" name="http">
<clobbers target="CordovaHttpPlugin" /> <clobbers target="cordova.plugin.http" />
</js-module> </js-module>
<!-- ios --> <!-- ios -->
@@ -30,7 +30,7 @@
<header-file src="src/ios/CordovaHttpPlugin.h" /> <header-file src="src/ios/CordovaHttpPlugin.h" />
<source-file src="src/ios/CordovaHttpPlugin.m" /> <source-file src="src/ios/CordovaHttpPlugin.m" />
<header-file src="src/ios/TextResponseSerializer.h" /> <header-file src="src/ios/TextResponseSerializer.h" />
<source-file src="src/ios/TextResponseSerializer.m" /> <source-file src="src/ios/TextResponseSerializer.m" />
@@ -62,22 +62,24 @@
<platform name="android"> <platform name="android">
<config-file target="res/xml/config.xml" parent="/*"> <config-file target="res/xml/config.xml" parent="/*">
<feature name="CordovaHttpPlugin"> <feature name="CordovaHttpPlugin">
<param name="android-package" value="com.synconset.CordovaHttpPlugin"/> <param name="android-package" value="com.synconset.cordovahttp.CordovaHttpPlugin"/>
</feature> </feature>
</config-file> </config-file>
<config-file target="AndroidManifest.xml" parent="/manifest"> <config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
</config-file> </config-file>
<source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttp.java" target-dir="src/com/synconset" /> <source-file src="src/android/com/github/kevinsawicki/http/HttpRequest.java" target-dir="src/com/github/kevinsawicki/http" />
<source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpGet.java" target-dir="src/com/synconset" /> <source-file src="src/android/com/github/kevinsawicki/http/TLSSocketFactory.java" target-dir="src/com/github/kevinsawicki/http" />
<source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpPost.java" target-dir="src/com/synconset" /> <source-file src="src/android/com/synconset/cordovahttp/CordovaHttp.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpHead.java" target-dir="src/com/synconset" /> <source-file src="src/android/com/synconset/cordovahttp/CordovaHttpDelete.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpUpload.java" target-dir="src/com/synconset" /> <source-file src="src/android/com/synconset/cordovahttp/CordovaHttpDownload.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpDownload.java" target-dir="src/com/synconset" /> <source-file src="src/android/com/synconset/cordovahttp/CordovaHttpGet.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/CordovaHTTP/CordovaHttpPlugin.java" target-dir="src/com/synconset" /> <source-file src="src/android/com/synconset/cordovahttp/CordovaHttpHead.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/CordovaHTTP/HttpRequest.java" target-dir="src/com/github/kevinsawicki/http" /> <source-file src="src/android/com/synconset/cordovahttp/CordovaHttpPlugin.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/CordovaHTTP/TLSSocketFactory.java" target-dir="src/com/github/kevinsawicki/http" /> <source-file src="src/android/com/synconset/cordovahttp/CordovaHttpPost.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpPut.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpUpload.java" target-dir="src/com/synconset/cordovahttp" />
</platform> </platform>
</plugin> </plugin>
@@ -259,11 +259,11 @@ public class HttpRequest {
private static final String CRLF = "\r\n"; private static final String CRLF = "\r\n";
private static final String[] EMPTY_STRINGS = new String[0]; private static final String[] EMPTY_STRINGS = new String[0];
private static SSLSocketFactory PINNED_FACTORY; private static SSLSocketFactory PINNED_FACTORY;
private static SSLSocketFactory TRUSTED_FACTORY; private static SSLSocketFactory TRUSTED_FACTORY;
private static ArrayList<Certificate> PINNED_CERTS; private static ArrayList<Certificate> PINNED_CERTS;
private static HostnameVerifier TRUSTED_VERIFIER; private static HostnameVerifier TRUSTED_VERIFIER;
@@ -274,7 +274,7 @@ public class HttpRequest {
else else
return CHARSET_UTF8; return CHARSET_UTF8;
} }
private static SSLSocketFactory getPinnedFactory() private static SSLSocketFactory getPinnedFactory()
throws HttpRequestException { throws HttpRequestException {
if (PINNED_FACTORY != null) { if (PINNED_FACTORY != null) {
@@ -305,7 +305,7 @@ public class HttpRequest {
try { try {
SSLContext context = SSLContext.getInstance("TLS"); SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom()); context.init(null, trustAllCerts, new SecureRandom());
if (android.os.Build.VERSION.SDK_INT < 20) { if (android.os.Build.VERSION.SDK_INT < 20) {
TRUSTED_FACTORY = new TLSSocketFactory(context); TRUSTED_FACTORY = new TLSSocketFactory(context);
} else { } else {
@@ -429,8 +429,8 @@ public class HttpRequest {
else else
CONNECTION_FACTORY = connectionFactory; CONNECTION_FACTORY = connectionFactory;
} }
/** /**
* Add a certificate to test against when using ssl pinning. * Add a certificate to test against when using ssl pinning.
* *
@@ -447,27 +447,27 @@ public class HttpRequest {
String keyStoreType = KeyStore.getDefaultType(); String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType); KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null); keyStore.load(null, null);
for (int i = 0; i < PINNED_CERTS.size(); i++) { for (int i = 0; i < PINNED_CERTS.size(); i++) {
keyStore.setCertificateEntry("CA" + i, PINNED_CERTS.get(i)); keyStore.setCertificateEntry("CA" + i, PINNED_CERTS.get(i));
} }
// Create a TrustManager that trusts the CAs in our KeyStore // Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore); tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager // Create an SSLContext that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS"); SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null); sslContext.init(null, tmf.getTrustManagers(), null);
if (android.os.Build.VERSION.SDK_INT < 20) { if (android.os.Build.VERSION.SDK_INT < 20) {
PINNED_FACTORY = new TLSSocketFactory(sslContext); PINNED_FACTORY = new TLSSocketFactory(sslContext);
} else { } else {
PINNED_FACTORY = sslContext.getSocketFactory(); PINNED_FACTORY = sslContext.getSocketFactory();
} }
} }
/** /**
* Add a certificate to test against when using ssl pinning. * Add a certificate to test against when using ssl pinning.
* *
@@ -3256,7 +3256,7 @@ public class HttpRequest {
form(entry, charset); form(entry, charset);
return this; return this;
} }
/** /**
* Configure HTTPS connection to trust only certain certificates * Configure HTTPS connection to trust only certain certificates
* <p> * <p>
@@ -3275,7 +3275,7 @@ public class HttpRequest {
} }
return this; return this;
} }
/** /**
* Configure HTTPS connection to trust all certificates * Configure HTTPS connection to trust all certificates
* <p> * <p>
@@ -4,8 +4,6 @@ import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.Socket; import java.net.Socket;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocket;
@@ -60,4 +58,4 @@ public class TLSSocketFactory extends SSLSocketFactory {
} }
return socket; return socket;
} }
} }
@@ -1,47 +1,41 @@
/** /**
* A HTTP plugin for Cordova / Phonegap * A HTTP plugin for Cordova / Phonegap
*/ */
package com.synconset; package com.synconset.cordovahttp;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import org.apache.cordova.CallbackContext; import org.apache.cordova.CallbackContext;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest; import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
public class CordovaHttpGet extends CordovaHttp implements Runnable { class CordovaHttpDelete extends CordovaHttp implements Runnable {
public CordovaHttpGet(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) { public CordovaHttpDelete(String urlString, JSONObject data, JSONObject headers, CallbackContext callbackContext) {
super(urlString, params, headers, callbackContext); super(urlString, data, headers, callbackContext);
} }
@Override @Override
public void run() { public void run() {
try { try {
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParams(), false); HttpRequest request = HttpRequest.delete(this.getUrlString(), this.getParamsMap(), false);
this.setupSecurity(request); this.setupSecurity(request);
request.acceptCharset(CHARSET); request.acceptCharset(CHARSET);
request.headers(this.getHeaders()); request.headers(this.getHeadersMap());
int code = request.code(); int code = request.code();
String body = request.body(CHARSET); String body = request.body(CHARSET);
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
this.addResponseHeaders(request, response); this.addResponseHeaders(request, response);
response.put("status", code); response.put("status", code);
if (code >= 200 && code < 300) { if (code >= 200 && code < 300) {
response.put("data", body); response.put("data", body);
this.getCallbackContext().success(response); this.getCallbackContext().success(response);
@@ -61,4 +55,4 @@ public class CordovaHttpGet extends CordovaHttp implements Runnable {
} }
} }
} }
} }
@@ -0,0 +1,64 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.UnknownHostException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import javax.net.ssl.SSLHandshakeException;
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, CallbackContext callbackContext) {
super(urlString, data, serializerName, headers, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.put(this.getUrlString());
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
if (new String("json").equals(this.getSerializerName())) {
request.contentType(request.CONTENT_TYPE_JSON, request.CHARSET_UTF8);
request.send(this.getParamsObject().toString());
} else {
request.form(this.getParamsMap());
}
int code = request.code();
String body = request.body(CHARSET);
JSONObject response = new JSONObject();
this.addResponseHeaders(request, response);
response.put("status", code);
if (code >= 200 && code < 300) {
response.put("data", body);
this.getCallbackContext().success(response);
} else {
response.put("error", body);
this.getCallbackContext().error(response);
}
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {
this.respondWithError("There was an error with the request");
}
}
}
}
@@ -1,63 +1,58 @@
/** /**
* A HTTP plugin for Cordova / Phonegap * A HTTP plugin for Cordova / Phonegap
*/ */
package com.synconset; package com.synconset.cordovahttp;
import org.apache.cordova.CallbackContext; import org.apache.cordova.CallbackContext;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.HostnameVerifier;
import java.util.Iterator; import java.util.Iterator;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest; import com.github.kevinsawicki.http.HttpRequest;
public abstract class CordovaHttp { abstract class CordovaHttp {
protected static final String TAG = "CordovaHTTP"; protected static final String TAG = "CordovaHTTP";
protected static final String CHARSET = "UTF-8"; protected static final String CHARSET = "UTF-8";
private static AtomicBoolean sslPinning = new AtomicBoolean(false); private static AtomicBoolean sslPinning = new AtomicBoolean(false);
private static AtomicBoolean acceptAllCerts = new AtomicBoolean(false); private static AtomicBoolean acceptAllCerts = new AtomicBoolean(false);
private static AtomicBoolean validateDomainName = new AtomicBoolean(true); private static AtomicBoolean validateDomainName = new AtomicBoolean(true);
private String urlString; private String urlString;
private Map<?, ?> params; private JSONObject params;
private Map<String, String> headers; private String serializerName;
private JSONObject headers;
private CallbackContext callbackContext; private CallbackContext callbackContext;
public CordovaHttp(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) { public CordovaHttp(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext) {
this.urlString = urlString; this.urlString = urlString;
this.params = params; this.params = params;
this.serializerName = "default";
this.headers = headers; this.headers = headers;
this.callbackContext = callbackContext; this.callbackContext = callbackContext;
} }
public CordovaHttp(String urlString, JSONObject params, String serializerName, JSONObject headers, CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.serializerName = serializerName;
this.headers = headers;
this.callbackContext = callbackContext;
}
public static void enableSSLPinning(boolean enable) { public static void enableSSLPinning(boolean enable) {
sslPinning.set(enable); sslPinning.set(enable);
if (enable) { if (enable) {
acceptAllCerts.set(false); acceptAllCerts.set(false);
} }
} }
public static void acceptAllCerts(boolean accept) { public static void acceptAllCerts(boolean accept) {
acceptAllCerts.set(accept); acceptAllCerts.set(accept);
if (accept) { if (accept) {
@@ -72,19 +67,31 @@ public abstract class CordovaHttp {
protected String getUrlString() { protected String getUrlString() {
return this.urlString; return this.urlString;
} }
protected Map<?, ?> getParams() { protected JSONObject getParamsObject() {
return this.params; return this.params;
} }
protected Map<String, String> getHeaders() { protected String getSerializerName() {
return this.serializerName;
}
protected HashMap<String, Object> getParamsMap() throws JSONException {
return this.getMapFromJSONObject(this.params);
}
protected JSONObject getHeadersObject() {
return this.headers; return this.headers;
} }
protected HashMap<String, String> getHeadersMap() throws JSONException {
return this.getStringMapFromJSONObject(this.headers);
}
protected CallbackContext getCallbackContext() { protected CallbackContext getCallbackContext() {
return this.callbackContext; return this.callbackContext;
} }
protected HttpRequest setupSecurity(HttpRequest request) { protected HttpRequest setupSecurity(HttpRequest request) {
if (acceptAllCerts.get()) { if (acceptAllCerts.get()) {
request.trustAllCerts(); request.trustAllCerts();
@@ -97,7 +104,7 @@ public abstract class CordovaHttp {
} }
return request; return request;
} }
protected void respondWithError(int status, String msg) { protected void respondWithError(int status, String msg) {
try { try {
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
@@ -108,7 +115,7 @@ public abstract class CordovaHttp {
this.callbackContext.error(msg); this.callbackContext.error(msg);
} }
} }
protected void respondWithError(String msg) { protected void respondWithError(String msg) {
this.respondWithError(500, msg); this.respondWithError(500, msg);
} }
@@ -125,4 +132,26 @@ public abstract class CordovaHttp {
} }
response.put("headers", new JSONObject(parsed_headers)); response.put("headers", new JSONObject(parsed_headers));
} }
protected HashMap<String, String> getStringMapFromJSONObject(JSONObject object) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
Iterator<?> i = object.keys();
while (i.hasNext()) {
String key = (String)i.next();
map.put(key, object.getString(key));
}
return map;
}
protected HashMap<String, Object> getMapFromJSONObject(JSONObject object) throws JSONException {
HashMap<String, Object> map = new HashMap<String, Object>();
Iterator<?> i = object.keys();
while(i.hasNext()) {
String key = (String)i.next();
map.put(key, object.get(key));
}
return map;
}
} }
@@ -1,9 +1,7 @@
/** /**
* A HTTP plugin for Cordova / Phonegap * A HTTP plugin for Cordova / Phonegap
*/ */
package com.synconset; package com.synconset.cordovahttp;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest; import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
@@ -12,7 +10,6 @@ import java.io.File;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Map;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
@@ -22,23 +19,23 @@ import org.apache.cordova.file.FileUtils;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
public class CordovaHttpDownload extends CordovaHttp implements Runnable { class CordovaHttpDownload extends CordovaHttp implements Runnable {
private String filePath; private String filePath;
public CordovaHttpDownload(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext, String filePath) { public CordovaHttpDownload(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, String filePath) {
super(urlString, params, headers, callbackContext); super(urlString, params, headers, callbackContext);
this.filePath = filePath; this.filePath = filePath;
} }
@Override @Override
public void run() { public void run() {
try { try {
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParams(), true); HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParamsMap(), true);
this.setupSecurity(request); this.setupSecurity(request);
request.acceptCharset(CHARSET); request.acceptCharset(CHARSET);
request.headers(this.getHeaders()); request.headers(this.getHeadersMap());
int code = request.code(); int code = request.code();
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
this.addResponseHeaders(request, response); this.addResponseHeaders(request, response);
response.put("status", code); response.put("status", code);
@@ -1,40 +1,41 @@
/** /**
* A HTTP plugin for Cordova / Phonegap * A HTTP plugin for Cordova / Phonegap
*/ */
package com.synconset; package com.synconset.cordovahttp;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Map;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import android.util.Log; import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import com.github.kevinsawicki.http.HttpRequest; import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
public class CordovaHttpPost extends CordovaHttp implements Runnable { class CordovaHttpGet extends CordovaHttp implements Runnable {
public CordovaHttpPost(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) { public CordovaHttpGet(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext) {
super(urlString, params, headers, callbackContext); super(urlString, params, headers, callbackContext);
} }
@Override @Override
public void run() { public void run() {
try { try {
HttpRequest request = HttpRequest.post(this.getUrlString()); HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParamsMap(), false);
this.setupSecurity(request); this.setupSecurity(request);
request.acceptCharset(CHARSET); request.acceptCharset(CHARSET);
request.headers(this.getHeaders()); request.headers(this.getHeadersMap());
request.form(this.getParams());
int code = request.code(); int code = request.code();
String body = request.body(CHARSET); String body = request.body(CHARSET);
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
this.addResponseHeaders(request, response); this.addResponseHeaders(request, response);
response.put("status", code); response.put("status", code);
if (code >= 200 && code < 300) { if (code >= 200 && code < 300) {
response.put("data", body); response.put("data", body);
this.getCallbackContext().success(response); this.getCallbackContext().success(response);
@@ -44,7 +45,7 @@ public class CordovaHttpPost extends CordovaHttp implements Runnable {
} }
} catch (JSONException e) { } catch (JSONException e) {
this.respondWithError("There was an error generating the response"); this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) { } catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) { if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved"); this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SSLHandshakeException) { } else if (e.getCause() instanceof SSLHandshakeException) {
@@ -1,18 +1,9 @@
/** /**
* A HTTP plugin for Cordova / Phonegap * A HTTP plugin for Cordova / Phonegap
*/ */
package com.synconset; package com.synconset.cordovahttp;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
@@ -20,27 +11,29 @@ import org.apache.cordova.CallbackContext;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest; import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
public class CordovaHttpHead extends CordovaHttp implements Runnable { class CordovaHttpHead extends CordovaHttp implements Runnable {
public CordovaHttpHead(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext) { public CordovaHttpHead(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext) {
super(urlString, params, headers, callbackContext); super(urlString, params, headers, callbackContext);
} }
@Override @Override
public void run() { public void run() {
try { try {
HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParams(), true); HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), true);
this.setupSecurity(request); this.setupSecurity(request);
request.acceptCharset(CHARSET); request.acceptCharset(CHARSET);
request.headers(this.getHeaders()); request.headers(this.getHeadersMap());
int code = request.code(); int code = request.code();
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
this.addResponseHeaders(request, response); this.addResponseHeaders(request, response);
response.put("status", code); response.put("status", code);
if (code >= 200 && code < 300) { if (code >= 200 && code < 300) {
// no 'body' to return for HEAD request // no 'body' to return for HEAD request
this.getCallbackContext().success(response); this.getCallbackContext().success(response);
@@ -61,4 +54,4 @@ public class CordovaHttpHead extends CordovaHttp implements Runnable {
} }
} }
} }
} }
@@ -1,39 +1,26 @@
/** /**
* A HTTP plugin for Cordova / Phonegap * A HTTP plugin for Cordova / Phonegap
*/ */
package com.synconset; package com.synconset.cordovahttp;
import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.HashMap;
import javax.net.ssl.HttpsURLConnection; import java.security.GeneralSecurityException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory; import java.util.ArrayList;
import javax.net.ssl.TrustManager;
import javax.net.ssl.HostnameVerifier;
import org.apache.cordova.CallbackContext; import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaWebView;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import android.content.res.AssetManager; import android.content.res.AssetManager;
import android.util.Base64;
import android.util.Log;
import com.github.kevinsawicki.http.HttpRequest; import com.github.kevinsawicki.http.HttpRequest;
@@ -47,30 +34,43 @@ public class CordovaHttpPlugin extends CordovaPlugin {
@Override @Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("get")) { if (action.equals("post")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
CordovaHttpPost post = new CordovaHttpPost(urlString, params, serializerName, headers, callbackContext);
cordova.getThreadPool().execute(post);
} else if (action.equals("get")) {
String urlString = args.getString(0); String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1); JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2); JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params); CordovaHttpGet get = new CordovaHttpGet(urlString, params, headers, callbackContext);
HashMap<String, String> headersMap = this.getStringMapFromJSONObject(headers);
CordovaHttpGet get = new CordovaHttpGet(urlString, paramsMap, headersMap, callbackContext);
cordova.getThreadPool().execute(get); cordova.getThreadPool().execute(get);
} else if (action.equals("put")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
CordovaHttpPut put = new CordovaHttpPut(urlString, params, serializerName, headers, callbackContext);
cordova.getThreadPool().execute(put);
} else if (action.equals("delete")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
CordovaHttpDelete delete = new CordovaHttpDelete(urlString, params, headers, callbackContext);
cordova.getThreadPool().execute(delete);
} else if (action.equals("head")) { } else if (action.equals("head")) {
String urlString = args.getString(0); String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1); JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2); JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params); CordovaHttpHead head = new CordovaHttpHead(urlString, params, headers, callbackContext);
HashMap<String, String> headersMap = this.getStringMapFromJSONObject(headers);
CordovaHttpHead head = new CordovaHttpHead(urlString, paramsMap, headersMap, callbackContext);
cordova.getThreadPool().execute(head); cordova.getThreadPool().execute(head);
} else if (action.equals("post")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params);
HashMap<String, String> headersMap = this.getStringMapFromJSONObject(headers);
CordovaHttpPost post = new CordovaHttpPost(urlString, paramsMap, headersMap, callbackContext);
cordova.getThreadPool().execute(post);
} else if (action.equals("enableSSLPinning")) { } else if (action.equals("enableSSLPinning")) {
try { try {
boolean enable = args.getBoolean(0); boolean enable = args.getBoolean(0);
@@ -82,30 +82,30 @@ public class CordovaHttpPlugin extends CordovaPlugin {
} }
} else if (action.equals("acceptAllCerts")) { } else if (action.equals("acceptAllCerts")) {
boolean accept = args.getBoolean(0); boolean accept = args.getBoolean(0);
CordovaHttp.acceptAllCerts(accept); CordovaHttp.acceptAllCerts(accept);
callbackContext.success(); callbackContext.success();
} else if (action.equals("validateDomainName")) { } else if (action.equals("validateDomainName")) {
boolean accept = args.getBoolean(0); boolean accept = args.getBoolean(0);
CordovaHttp.validateDomainName(accept); CordovaHttp.validateDomainName(accept);
callbackContext.success(); callbackContext.success();
} else if (action.equals("uploadFile")) { } else if (action.equals("uploadFile")) {
String urlString = args.getString(0); String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1); JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2); JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params);
HashMap<String, String> headersMap = this.getStringMapFromJSONObject(headers);
String filePath = args.getString(3); String filePath = args.getString(3);
String name = args.getString(4); String name = args.getString(4);
CordovaHttpUpload upload = new CordovaHttpUpload(urlString, paramsMap, headersMap, callbackContext, filePath, name); CordovaHttpUpload upload = new CordovaHttpUpload(urlString, params, headers, callbackContext, filePath, name);
cordova.getThreadPool().execute(upload); cordova.getThreadPool().execute(upload);
} else if (action.equals("downloadFile")) { } else if (action.equals("downloadFile")) {
String urlString = args.getString(0); String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1); JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2); JSONObject headers = args.getJSONObject(2);
HashMap<?, ?> paramsMap = this.getMapFromJSONObject(params);
HashMap<String, String> headersMap = this.getStringMapFromJSONObject(headers);
String filePath = args.getString(3); String filePath = args.getString(3);
CordovaHttpDownload download = new CordovaHttpDownload(urlString, paramsMap, headersMap, callbackContext, filePath); CordovaHttpDownload download = new CordovaHttpDownload(urlString, params, headers, callbackContext, filePath);
cordova.getThreadPool().execute(download); cordova.getThreadPool().execute(download);
} else { } else {
return false; return false;
@@ -149,26 +149,4 @@ public class CordovaHttpPlugin extends CordovaPlugin {
CordovaHttp.enableSSLPinning(false); CordovaHttp.enableSSLPinning(false);
} }
} }
private HashMap<String, String> getStringMapFromJSONObject(JSONObject object) throws JSONException {
HashMap<String, String> map = new HashMap<String, String>();
Iterator<?> i = object.keys();
while (i.hasNext()) {
String key = (String)i.next();
map.put(key, object.getString(key));
}
return map;
}
private HashMap<String, Object> getMapFromJSONObject(JSONObject object) throws JSONException {
HashMap<String, Object> map = new HashMap<String, Object>();
Iterator<?> i = object.keys();
while(i.hasNext()) {
String key = (String)i.next();
map.put(key, object.get(key));
}
return map;
}
} }
@@ -0,0 +1,64 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.UnknownHostException;
import org.apache.cordova.CallbackContext;
import org.json.JSONException;
import org.json.JSONObject;
import javax.net.ssl.SSLHandshakeException;
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, CallbackContext callbackContext) {
super(urlString, params, serializerName, headers, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.post(this.getUrlString());
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
if (new String("json").equals(this.getSerializerName())) {
request.contentType(request.CONTENT_TYPE_JSON, request.CHARSET_UTF8);
request.send(this.getParamsObject().toString());
} else {
request.form(this.getParamsMap());
}
int code = request.code();
String body = request.body(CHARSET);
JSONObject response = new JSONObject();
this.addResponseHeaders(request, response);
response.put("status", code);
if (code >= 200 && code < 300) {
response.put("data", body);
this.getCallbackContext().success(response);
} else {
response.put("error", body);
this.getCallbackContext().error(response);
}
} catch (JSONException e) {
this.respondWithError("There was an error generating the response");
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {
this.respondWithError("There was an error with the request");
}
}
}
}
@@ -1,57 +1,65 @@
/** /**
* A HTTP plugin for Cordova / Phonegap * A HTTP plugin for Cordova / Phonegap
*/ */
package com.synconset; package com.synconset.cordovahttp;
import java.io.File; import java.io.File;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import org.apache.cordova.CallbackContext; import org.apache.cordova.CallbackContext;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLHandshakeException;
import android.util.Log;
import android.webkit.MimeTypeMap; import android.webkit.MimeTypeMap;
import com.github.kevinsawicki.http.HttpRequest; import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
public class CordovaHttpUpload extends CordovaHttp implements Runnable { class CordovaHttpUpload extends CordovaHttp implements Runnable {
private String filePath; private String filePath;
private String name; private String name;
public CordovaHttpUpload(String urlString, Map<?, ?> params, Map<String, String> headers, CallbackContext callbackContext, String filePath, String name) { public CordovaHttpUpload(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, String filePath, String name) {
super(urlString, params, headers, callbackContext); super(urlString, params, headers, callbackContext);
this.filePath = filePath; this.filePath = filePath;
this.name = name; this.name = name;
} }
@Override @Override
public void run() { public void run() {
try { try {
HttpRequest request = HttpRequest.post(this.getUrlString()); HttpRequest request = HttpRequest.post(this.getUrlString());
this.setupSecurity(request); this.setupSecurity(request);
request.acceptCharset(CHARSET); request.acceptCharset(CHARSET);
request.headers(this.getHeaders()); request.headers(this.getHeadersMap());
URI uri = new URI(filePath); URI uri = new URI(filePath);
int index = filePath.lastIndexOf('/');
String filename = filePath.substring(index + 1); int filenameIndex = filePath.lastIndexOf('/');
index = filePath.lastIndexOf('.'); String filename = filePath.substring(filenameIndex + 1);
String ext = filePath.substring(index + 1);
int extIndex = filePath.lastIndexOf('.');
String ext = filePath.substring(extIndex + 1);
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton(); MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String mimeType = mimeTypeMap.getMimeTypeFromExtension(ext); String mimeType = mimeTypeMap.getMimeTypeFromExtension(ext);
request.part(this.name, filename, mimeType, new File(uri)); request.part(this.name, filename, mimeType, new File(uri));
Set<?> set = (Set<?>)this.getParams().entrySet(); Set<?> set = (Set<?>)this.getParamsMap().entrySet();
Iterator<?> i = set.iterator(); Iterator<?> i = set.iterator();
while (i.hasNext()) { while (i.hasNext()) {
Entry<?, ?> e = (Entry<?, ?>)i.next(); Entry<?, ?> e = (Entry<?, ?>)i.next();
String key = (String)e.getKey(); String key = (String)e.getKey();
@@ -65,13 +73,15 @@ public class CordovaHttpUpload extends CordovaHttp implements Runnable {
return; return;
} }
} }
int code = request.code(); int code = request.code();
String body = request.body(CHARSET); String body = request.body(CHARSET);
JSONObject response = new JSONObject(); JSONObject response = new JSONObject();
this.addResponseHeaders(request, response); this.addResponseHeaders(request, response);
response.put("status", code); response.put("status", code);
if (code >= 200 && code < 300) { if (code >= 200 && code < 300) {
response.put("data", body); response.put("data", body);
this.getCallbackContext().success(response); this.getCallbackContext().success(response);
+3 -1
View File
@@ -9,7 +9,9 @@
- (void)validateDomainName:(CDVInvokedUrlCommand*)command; - (void)validateDomainName:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command; - (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command; - (void)get:(CDVInvokedUrlCommand*)command;
- (void)put:(CDVInvokedUrlCommand*)command;
- (void)delete:(CDVInvokedUrlCommand*)command;
- (void)uploadFile:(CDVInvokedUrlCommand*)command; - (void)uploadFile:(CDVInvokedUrlCommand*)command;
- (void)downloadFile:(CDVInvokedUrlCommand*)command; - (void)downloadFile:(CDVInvokedUrlCommand*)command;
@end @end
+86 -20
View File
@@ -19,8 +19,15 @@
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
} }
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager { - (void)setRequestSerializer:(NSString*)serializerName forManager:(AFHTTPSessionManager*)manager {
if ([serializerName isEqualToString:@"json"]) {
manager.requestSerializer = [AFJSONRequestSerializer serializer];
} else {
manager.requestSerializer = [AFHTTPRequestSerializer serializer]; manager.requestSerializer = [AFHTTPRequestSerializer serializer];
}
}
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager {
[headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [headers enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[manager.requestSerializer setValue:obj forHTTPHeaderField:key]; [manager.requestSerializer setValue:obj forHTTPHeaderField:key];
}]; }];
@@ -41,7 +48,7 @@
} else { } else {
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
} }
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} }
@@ -49,9 +56,9 @@
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command { - (void)acceptAllCerts:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil; CDVPluginResult* pluginResult = nil;
bool allow = [[command.arguments objectAtIndex:0] boolValue]; bool allow = [[command.arguments objectAtIndex:0] boolValue];
securityPolicy.allowInvalidCertificates = allow; securityPolicy.allowInvalidCertificates = allow;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} }
@@ -59,9 +66,9 @@
- (void)validateDomainName:(CDVInvokedUrlCommand*)command { - (void)validateDomainName:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil; CDVPluginResult* pluginResult = nil;
bool validate = [[command.arguments objectAtIndex:0] boolValue]; bool validate = [[command.arguments objectAtIndex:0] boolValue];
securityPolicy.validatesDomainName = validate; securityPolicy.validatesDomainName = validate;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} }
@@ -71,9 +78,11 @@
manager.securityPolicy = securityPolicy; manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0]; NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1]; NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2]; NSString *serializerName = [command.arguments objectAtIndex:2];
NSDictionary *headers = [command.arguments objectAtIndex:3];
[self setRequestSerializer: serializerName forManager: manager];
[self setRequestHeaders: headers forManager: manager]; [self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self; CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer]; manager.responseSerializer = [TextResponseSerializer serializer];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) { [manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
@@ -98,10 +107,11 @@
NSString *url = [command.arguments objectAtIndex:0]; NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1]; NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2]; NSDictionary *headers = [command.arguments objectAtIndex:2];
[self setRequestSerializer: @"default" forManager: manager];
[self setRequestHeaders: headers forManager: manager]; [self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self; CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer]; manager.responseSerializer = [TextResponseSerializer serializer];
[manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) { [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
@@ -119,6 +129,62 @@
}]; }];
} }
- (void)put:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSString *serializerName = [command.arguments objectAtIndex:2];
NSDictionary *headers = [command.arguments objectAtIndex:3];
[self setRequestSerializer: serializerName forManager: manager];
[self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager PUT:url parameters:parameters success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[dictionary setObject:responseObject forKey:@"data"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
[dictionary setObject:errResponse forKey:@"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void)delete:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2];
[self setRequestSerializer: @"default" forManager: manager];
[self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager DELETE:url parameters:parameters success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[dictionary setObject:responseObject forKey:@"data"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
[dictionary setObject:errResponse forKey:@"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void)head:(CDVInvokedUrlCommand*)command { - (void)head:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy; manager.securityPolicy = securityPolicy;
@@ -126,9 +192,9 @@
NSDictionary *parameters = [command.arguments objectAtIndex:1]; NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2]; NSDictionary *headers = [command.arguments objectAtIndex:2];
[self setRequestHeaders: headers forManager: manager]; [self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self; CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager HEAD:url parameters:parameters success:^(NSURLSessionTask *task) { [manager HEAD:url parameters:parameters success:^(NSURLSessionTask *task) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
@@ -154,11 +220,11 @@
NSDictionary *headers = [command.arguments objectAtIndex:2]; NSDictionary *headers = [command.arguments objectAtIndex:2];
NSString *filePath = [command.arguments objectAtIndex: 3]; NSString *filePath = [command.arguments objectAtIndex: 3];
NSString *name = [command.arguments objectAtIndex: 4]; NSString *name = [command.arguments objectAtIndex: 4];
NSURL *fileURL = [NSURL URLWithString: filePath]; NSURL *fileURL = [NSURL URLWithString: filePath];
[self setRequestHeaders: headers forManager: manager]; [self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self; CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer]; manager.responseSerializer = [TextResponseSerializer serializer];
[manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
@@ -195,13 +261,13 @@
NSDictionary *parameters = [command.arguments objectAtIndex:1]; NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2]; NSDictionary *headers = [command.arguments objectAtIndex:2];
NSString *filePath = [command.arguments objectAtIndex: 3]; NSString *filePath = [command.arguments objectAtIndex: 3];
[self setRequestHeaders: headers forManager: manager]; [self setRequestHeaders: headers forManager: manager];
if ([filePath hasPrefix:@"file://"]) { if ([filePath hasPrefix:@"file://"]) {
filePath = [filePath substringFromIndex:7]; filePath = [filePath substringFromIndex:7];
} }
CordovaHttpPlugin* __weak weakSelf = self; CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [AFHTTPResponseSerializer serializer]; manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) { [manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
@@ -229,7 +295,7 @@
*/ */
// Download response is okay; begin streaming output to file // Download response is okay; begin streaming output to file
NSString* parentPath = [filePath stringByDeletingLastPathComponent]; NSString* parentPath = [filePath stringByDeletingLastPathComponent];
// create parent directories if needed // create parent directories if needed
NSError *error; NSError *error;
if ([[NSFileManager defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) { if ([[NSFileManager defaultManager] createDirectoryAtPath:parentPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) {
@@ -253,7 +319,7 @@
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; [weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
return; return;
} }
id filePlugin = [self.commandDelegate getCommandInstance:@"File"]; id filePlugin = [self.commandDelegate getCommandInstance:@"File"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task]; [self setResults: dictionary withTask: task];
-175
View File
@@ -1,175 +0,0 @@
/*global angular*/
/*
* An HTTP Plugin for PhoneGap.
*/
var exec = require('cordova/exec');
// Thanks Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function mergeHeaders(globalHeaders, localHeaders) {
var globalKeys = Object.keys(globalHeaders);
var key;
for (var i = 0; i < globalKeys.length; i++) {
key = globalKeys[i];
if (!localHeaders.hasOwnProperty(key)) {
localHeaders[key] = globalHeaders[key];
}
}
return localHeaders;
}
var http = {
headers: {},
sslPinning: false,
getBasicAuthHeader: function(username, password) {
return {'Authorization': 'Basic ' + b64EncodeUnicode(username + ':' + password)};
},
useBasicAuth: function(username, password) {
this.headers.Authorization = 'Basic ' + b64EncodeUnicode(username + ':' + password);
},
setHeader: function(header, value) {
this.headers[header] = value;
},
enableSSLPinning: function(enable, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "enableSSLPinning", [enable]);
},
acceptAllCerts: function(allow, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "acceptAllCerts", [allow]);
},
validateDomainName: function(validate, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "validateDomainName", [validate]);
},
post: function(url, params, headers, success, failure) {
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, "CordovaHttpPlugin", "post", [url, params, headers]);
},
get: function(url, params, headers, success, failure) {
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, "CordovaHttpPlugin", "get", [url, params, headers]);
},
head: function(url, params, headers, success, failure) {
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, "CordovaHttpPlugin", "head", [url, params, headers]);
},
uploadFile: function(url, params, headers, filePath, name, success, failure) {
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, "CordovaHttpPlugin", "uploadFile", [url, params, headers, filePath, name]);
},
downloadFile: function(url, params, headers, filePath, success, failure) {
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Modified by Andrew Stephan for Sync OnSet
*
*/
headers = mergeHeaders(this.headers, headers);
var win = function(result) {
var entry = new (require('cordova-plugin-file.FileEntry'))();
entry.isDirectory = false;
entry.isFile = true;
entry.name = result.file.name;
entry.fullPath = result.file.fullPath;
entry.filesystem = new FileSystem(result.file.filesystemName || (result.file.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
entry.nativeURL = result.file.nativeURL;
success(entry);
};
return exec(win, failure, "CordovaHttpPlugin", "downloadFile", [url, params, headers, filePath]);
}
};
module.exports = http;
if (typeof angular !== "undefined") {
angular.module('cordovaHTTP', []).factory('cordovaHTTP', function($timeout, $q) {
function makePromise(fn, args, async) {
var deferred = $q.defer();
var success = function(response) {
if (async) {
$timeout(function() {
deferred.resolve(response);
});
} else {
deferred.resolve(response);
}
};
var fail = function(response) {
if (async) {
$timeout(function() {
deferred.reject(response);
});
} else {
deferred.reject(response);
}
};
args.push(success);
args.push(fail);
fn.apply(http, args);
return deferred.promise;
}
var cordovaHTTP = {
getBasicAuthHeader: http.getBasicAuthHeader,
useBasicAuth: function(username, password) {
return http.useBasicAuth(username, password);
},
setHeader: function(header, value) {
return http.setHeader(header, value);
},
enableSSLPinning: function(enable) {
return makePromise(http.enableSSLPinning, [enable]);
},
acceptAllCerts: function(allow) {
return makePromise(http.acceptAllCerts, [allow]);
},
validateDomainName: function(validate) {
return makePromise(http.validateDomainName, [validate]);
},
post: function(url, params, headers) {
return makePromise(http.post, [url, params, headers], true);
},
get: function(url, params, headers) {
return makePromise(http.get, [url, params, headers], true);
},
head: function(url, params, headers) {
return makePromise(http.head, [url, params, headers], true);
},
uploadFile: function(url, params, headers, filePath, name) {
return makePromise(http.uploadFile, [url, params, headers, filePath, name], true);
},
downloadFile: function(url, params, headers, filePath) {
return makePromise(http.downloadFile, [url, params, headers, filePath], true);
}
};
return cordovaHTTP;
});
} else {
window.cordovaHTTP = http;
}
+217
View File
@@ -0,0 +1,217 @@
/*global angular*/
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
* Modified by Andrew Stephan for Sync OnSet
* Modified by Sefa Ilkimen:
* - added configurable params serializer
*
*/
/*
* An HTTP Plugin for PhoneGap.
*/
var exec = require('cordova/exec');
var validSerializers = ['urlencoded', 'json'];
// Thanks Mozilla: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_.22Unicode_Problem.22
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
function mergeHeaders(globalHeaders, localHeaders) {
var globalKeys = Object.keys(globalHeaders);
var key;
for (var i = 0; i < globalKeys.length; i++) {
key = globalKeys[i];
if (!localHeaders.hasOwnProperty(key)) {
localHeaders[key] = globalHeaders[key];
}
}
return localHeaders;
}
function checkSerializer(serializer) {
serializer = serializer || '';
serializer = serializer.trim().toLowerCase();
if (validSerializers.indexOf(serializer) > -1) {
return serializer;
}
return serializer[0];
}
var http = {
headers: {},
dataSerializer: 'urlencoded',
sslPinning: false,
getBasicAuthHeader: function (username, password) {
return {'Authorization': 'Basic ' + b64EncodeUnicode(username + ':' + password)};
},
useBasicAuth: function (username, password) {
this.headers.Authorization = 'Basic ' + b64EncodeUnicode(username + ':' + password);
},
setHeader: function (header, value) {
this.headers[header] = value;
},
setDataSerializer: function (serializer) {
this.dataSerializer = checkSerializer(serializer);
},
enableSSLPinning: function (enable, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'enableSSLPinning', [enable]);
},
acceptAllCerts: function (allow, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'acceptAllCerts', [allow]);
},
validateDomainName: function (validate, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'validateDomainName', [validate]);
},
post: function (url, data, headers, success, failure) {
data = data || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, 'CordovaHttpPlugin', 'post', [url, data, this.dataSerializer, headers]);
},
get: function (url, params, headers, success, failure) {
params = params || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, 'CordovaHttpPlugin', 'get', [url, params, headers]);
},
put: function (url, data, headers, success, failure) {
data = data || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, 'CordovaHttpPlugin', 'put', [url, data, this.dataSerializer, headers]);
},
delete: function (url, params, headers, success, failure) {
params = params || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, 'CordovaHttpPlugin', 'delete', [url, params, headers]);
},
head: function (url, params, headers, success, failure) {
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, 'CordovaHttpPlugin', 'head', [url, params, headers]);
},
uploadFile: function (url, params, headers, filePath, name, success, failure) {
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, 'CordovaHttpPlugin', 'uploadFile', [url, params, headers, filePath, name]);
},
downloadFile: function (url, params, headers, filePath, success, failure) {
headers = mergeHeaders(this.headers, headers);
var win = function (result) {
var entry = new (require('cordova-plugin-file.FileEntry'))();
entry.isDirectory = false;
entry.isFile = true;
entry.name = result.file.name;
entry.fullPath = result.file.fullPath;
entry.filesystem = new FileSystem(result.file.filesystemName || (result.file.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'));
entry.nativeURL = result.file.nativeURL;
success(entry);
};
return exec(win, failure, 'CordovaHttpPlugin', 'downloadFile', [url, params, headers, filePath]);
}
};
if (typeof angular !== 'undefined') {
angular.module('cordovaHTTP', []).factory('cordovaHTTP', function ($timeout, $q) {
function makePromise(fn, args, async) {
var deferred = $q.defer();
var success = function (response) {
if (async) {
$timeout(function () {
deferred.resolve(response);
});
} else {
deferred.resolve(response);
}
};
var fail = function (response) {
if (async) {
$timeout(function () {
deferred.reject(response);
});
} else {
deferred.reject(response);
}
};
args.push(success);
args.push(fail);
fn.apply(http, args);
return deferred.promise;
}
var cordovaHTTP = {
getBasicAuthHeader: http.getBasicAuthHeader,
useBasicAuth: function (username, password) {
return http.useBasicAuth(username, password);
},
setHeader: function (header, value) {
return http.setHeader(header, value);
},
setDataSerializer: function (serializer) {
return http.setParamSerializer(serializer);
},
enableSSLPinning: function (enable) {
return makePromise(http.enableSSLPinning, [enable]);
},
acceptAllCerts: function (allow) {
return makePromise(http.acceptAllCerts, [allow]);
},
validateDomainName: function (validate) {
return makePromise(http.validateDomainName, [validate]);
},
post: function (url, data, headers) {
return makePromise(http.post, [url, data, headers], true);
},
get: function (url, params, headers) {
return makePromise(http.get, [url, params, headers], true);
},
put: function (url, data, headers) {
return makePromise(http.put, [url, data, headers], true);
},
delete: function (url, params, headers) {
return makePromise(http.delete, [url, params, headers], true);
},
head: function (url, params, headers) {
return makePromise(http.head, [url, params, headers], true);
},
uploadFile: function (url, params, headers, filePath, name) {
return makePromise(http.uploadFile, [url, params, headers, filePath, name], true);
},
downloadFile: function (url, params, headers, filePath) {
return makePromise(http.downloadFile, [url, params, headers, filePath], true);
}
};
return cordovaHTTP;
});
}
module.exports = http;
-33
View File
@@ -1,33 +0,0 @@
{
"preferences": {
"tabSize": 2,
"wordWrap": true,
"useSoftTabs": true,
"gotoExclude": []
},
"packages": [
"gh:wymsee/zed-tools/mobile"
],
"modes": {
"javascript": {
"commands": {
"Tools:Check": {
"options": {
"globals": {
"angular": true,
"$": true,
"device": true,
"persistence": true,
"moment": true,
"sos": true,
"LocalFileSystem": true,
"Hammer": true,
"AnimationFrame": true,
"Bloodhound": true
}
}
}
}
}
}
}