Compare commits

...

32 Commits

Author SHA1 Message Date
Sefa Ilkimen
8b4c6de4b9 implemented PATCH method for iOS 2017-10-02 12:29:55 +02:00
Sefa Ilkimen
3138d423ee temporary removed patch method in www interface 2017-10-02 11:09:05 +02:00
Sefa Ilkimen
f0194ad55a Merge pull request #22 from akhatri/feature-patch-method-android
Feature patch method android
2017-10-02 10:50:12 +02:00
Akshat Khatri - AK
09da3c9a97 patch method android 2017-10-01 17:26:20 +11:00
Akshat Khatri - AK
52ccfc6aca Merge remote-tracking branch 'refs/remotes/silkimen/master' into feature-patch-method-android 2017-10-01 17:11:41 +11:00
Sefa Ilkimen
fc89a64675 update changelog and version number 2017-09-29 16:42:36 +02:00
Sefa Ilkimen
4954385361 - fix issue #16: removed build script and prebuild hook
- implement release script
2017-09-29 16:35:34 +02:00
Sefa Ilkimen
08554c02cb Merge pull request #21 from kesozjura/master
Add global redirection control
2017-09-29 15:51:56 +02:00
Martin Kasa
18a2fc0c69 temporary umd-tough-cookie.js fix 2017-09-29 14:44:44 +02:00
Martin Kasa
a4a6440bcb Add global redirection control
copied from https://github.com/wymsee/cordova-HTTP/pull/137
2017-09-29 14:36:00 +02:00
Akshat Khatri - AK
792515e1c6 patch method android 2017-09-29 21:02:44 +10:00
Sefa Ilkimen
66dc8ff2ca changed readme file 2017-09-26 10:48:06 +02:00
Sefa Ilkimen
91b35d561c - updated version number
- updated change log
2017-09-26 10:38:16 +02:00
Sefa Ilkimen
45c0f8937f Merge pull request #14 from RangerRick/fix-serialization
change setParamSerializer to setDataSerializer (fixes #13)
2017-09-26 11:15:19 +03:00
Sefa Ilkimen
b1c8427986 Merge pull request #15 from RangerRick/documentation-updates
add missing documentation
2017-09-26 11:05:34 +03:00
Benjamin Reed
91470725ee add missing documentation for setRequestTimeout, removeCookies, and head 2017-09-25 16:12:40 -04:00
Benjamin Reed
7cb41e0c1b change setParamSerializer to setDataSerializer (fixes #13) 2017-09-25 14:51:57 -04:00
Sefa Ilkimen
ee8cae88a9 updated change log 2017-09-12 19:05:23 +03:00
Sefa Ilkimen
aa8105948e Merge pull request #10 from DayBr3ak/master
fix gzip decompression when request header accepts gzip compression
2017-09-12 19:00:31 +03:00
ben
325a2e6200 fix gzip decompression when request header accepts gzip compression 2017-09-12 14:17:52 +02:00
Sefa Ilkimen
8ac8b95246 updated version number 2017-08-21 00:35:24 +02:00
Sefa Ilkimen
5a7f09bc44 updated change log 2017-08-21 00:31:50 +02:00
Sefa Ilkimen
308c49635b added build batch 2017-08-21 00:23:32 +02:00
Sefa Ilkimen
d2a5a113c6 added slack integration 2017-08-21 00:17:30 +02:00
Sefa Ilkimen
2c4ce6f8c7 fixed travis filename 2017-08-20 23:49:58 +02:00
Sefa Ilkimen
613593ba51 added travis integration (doing test installation) 2017-08-20 23:44:21 +02:00
Jochen Becker
a20821378b - if a request timed out the same error codes are returned for iOS and Android
- updated change log
2017-08-14 17:05:44 +02:00
Sefa Ilkimen
5535464db2 updated change log 2017-08-13 03:05:22 +02:00
Sefa Ilkimen
7ded66d4b8 fix issue #2: handling "expires" key case-insensitive 2017-08-13 03:01:52 +02:00
Jochen Becker
d84a222dda - added function "setRequestTimeout" to set the timeout for all further requests and to prevent to "wait forever" on Android in case the server is not responding
- updated change log
- incremented version for release
2017-08-10 10:03:38 +02:00
Jochen Becker
14eef1ca66 - convert response header keys to lowercase (iOS only)
- updated change log
- incremented version for release
2017-05-31 08:50:13 +02:00
Jochen Becker
cf5a684d51 - added a function to remove all cookies for a URL
- updated change log
- incremented version for release
2017-05-23 10:26:51 +02:00
28 changed files with 5434 additions and 99 deletions

2
.gitignore vendored
View File

@@ -1,4 +1,4 @@
node_modules/**
tags
.zedstate
/www/umd-tough-cookie.js
/temp

View File

@@ -1,2 +1,4 @@
tags
.zedstate
/scripts
/temp

6
.travis.yml Normal file
View File

@@ -0,0 +1,6 @@
language: node_js
node_js:
- lts/*
notifications:
slack:
secure: lXE+2AgsxZU5G5dI91LkMAIgo8MAWfdM7DB5UOtn5LpuNln+2FmJo1gOI7tkdmLOqpXTGYnpI2VyQN3H4nOF21YhuouzD1Sh8n2wtQg1iTm353kuQpqiVhSBX8ZJ7Be1e1G8OsnxoYOxbs4Zo9qI40EruwkvqLCBHWM5MRGyd4M7EFWwb9Z29VZN0y1Nt5g/c3bT76kdKmF+JCLur2OeEKxAity7sIKgZekSqeIMwEVLSxXnda6Dbjc/cg0MJ0iDArkD7iu6fz/Fcrrxgm/pUxjcgvqze7Gy5i31mjEfspnrglWV1cshMd48BTDKCJ2AMmxH8O3GPSWE2txjIvGRWUve7iViNylvmQCVz3Eyf99+4EuuVGa+5PSodQ/CqODx/65EwtcN3PE1tNz2puKOK8nrOJcFkcbG8KTHKUlQtHCkjitbykUnj/hvhLK5/oWlQYVOLWWrHwdGUh8FI8aFPVGjRjWbHbhdayjEIqxwr1ns+6mYrP1EFNXbaeZxnLNC59XpJl1ifuezqYAk7YEiU5j4rtC7YKgyQ3ueb7anOHTJoTMyDn8mpZXgwuyhoBaeEYytQVgRyMtL6Y5cP98Jn2kv0+vdne3rkk9/JEBTo32HOjvoij6rsqEvXC0LhUDJSNadOVdHht0jjoN6zBH37HIE5/3zysLlPcAcHAS83ow=

View File

@@ -1,5 +1,38 @@
# Changelog
## v1.6.0
- Feature #18: implemented PATCH method (thanks akhatri for android implementation)
- Feature #21: added redirection control (thanks to notsyncing and kesozjura)
- Fixed #16: cordova tries to run build script during plugin install
## v1.5.10
- Fixed #10: fix gzip decompression when request header accepts gzip compression (thanks to DayBr3ak)
- Fixed #13: fix angular integration for `setDataSerializer` (thanks to RangerRick)
- Added some missing documentation (thanks to RangerRick)
## v1.5.9
- Fixed case-sensitive folder name of Android source files
## v1.5.8
- Use the same error codes if a request timed out
## v1.5.7
- Fixed a bug in cookie handling (cookies containing an "Expires" string)
- Added setRequestTimeout function to set the timeout in seconds for all further requests
## v1.5.6
- All response header keys are converted to lowercase (iOS only)
## v1.5.5
- added a function to remove all cookies for a URL
## v1.5.4
- fixed an error if the response has no "headers" field

View File

@@ -1,5 +1,6 @@
The MIT License (MIT)
Copyright (c) 2017 Mobisys GmbH
Copyright (c) 2014 Wymsee, Inc
Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -18,4 +19,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
SOFTWARE.

View File

@@ -1,5 +1,6 @@
Cordova Advanced HTTP
=====================
[![Build Status](https://travis-ci.org/silkimen/cordova-plugin-advanced-http.svg?branch=master)](https://travis-ci.org/silkimen/cordova-plugin-advanced-http)
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).
@@ -55,6 +56,11 @@ Set a header for all future requests. Takes a header and a value.
cordovaHTTP.setHeader("Header", "Value");
### disableRedirect
If set to `true`, it won't follow redirects automatically. This is a global setting.
cordovaHTTP.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.
@@ -66,6 +72,11 @@ You can choose one of these two:
Caution: `urlencoded` does not support serializing deep structures whereas `json` does.
### setRequestTimeout
Set how long to wait for a request to respond, in seconds.
cordovaHTTP.setRequestTimeout(5.0);
### clearCookies
Clear the cookie store.
@@ -105,6 +116,11 @@ Whether or not to validate the domain name in the certificate. This defaults to
console.log('error :(');
});
### removeCookies
Remove all cookies associated with a given URL.
cordovaHTTP.removeCookies(url);
### post<a name="post"></a>
Execute a POST request. Takes a URL, data, and headers.
@@ -172,6 +188,9 @@ Execute a PUT request. Takes a URL, data, and headers. See the [post](#post) d
### 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.
### head
Execute a HEAD request. Takes a URL, parameters, and headers. See the [post](#post) documentation for details on what is returned on success and failure.
### 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.
@@ -203,21 +222,9 @@ Downloads a file and saves it to the device. Takes a URL, parameters, headers,
## Libraries
This plugin utilizes some awesome open source networking libraries. These are both MIT licensed:
This plugin utilizes some awesome open source networking libraries. These are both MIT licensed:
- iOS - [AFNetworking](https://github.com/AFNetworking/AFNetworking)
- Android - [http-request](https://github.com/kevinsawicki/http-request)
We made a few modifications to http-request. They can be found in a separate repo here: https://github.com/wymsee/http-request
## License
The MIT License
Copyright (c) 2014 Wymsee, Inc
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
We made a few modifications to http-request.

View File

@@ -1,10 +1,9 @@
{
"name": "cordova-plugin-advanced-http",
"version": "1.5.4",
"version": "1.6.0",
"description": "Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning",
"scripts": {
"build": "cp node_modules/umd-tough-cookie/lib/umd-tough-cookie.js www/umd-tough-cookie.js",
"prepublish": "npm run build"
"test": "./scripts/test-installation.sh"
},
"cordova": {
"id": "cordova-plugin-advanced-http",
@@ -50,6 +49,7 @@
},
"homepage": "https://github.com/silkimen/cordova-plugin-advanced-http#readme",
"devDependencies": {
"cordova": "7.0.1",
"umd-tough-cookie": "2.3.2"
}
}

View File

@@ -2,7 +2,7 @@
<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.5.4">
version="1.5.10">
<name>Advanced HTTP plugin</name>
@@ -90,6 +90,7 @@
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpPlugin.java" target-dir="src/com/synconset/cordovahttp" />
<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/CordovaHttpPatch.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpUpload.java" target-dir="src/com/synconset/cordovahttp" />
</platform>
</plugin>

8
release.sh Executable file
View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -e
VERSION=$(node -e "console.log(require('./package.json').version)")
./scripts/update-tough-cookie.sh
npm publish
git tag "v$VERSION"

12
scripts/test-installation.sh Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
CDV=$ROOT/node_modules/.bin/cordova
rm -rf $ROOT/temp
$CDV create $ROOT/temp
cd $ROOT/temp
$CDV platforms add android
$CDV platforms add ios
$CDV plugins add $ROOT

8
scripts/update-tough-cookie.sh Executable file
View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -e
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"/..
cd $ROOT
npm i
cp node_modules/umd-tough-cookie/lib/umd-tough-cookie.js www/umd-tough-cookie.js

View File

@@ -236,6 +236,11 @@ public class HttpRequest {
*/
public static final String METHOD_POST = "POST";
/**
* 'PATCH' request method
*/
public static final String METHOD_PATCH = "PATCH";
/**
* 'PUT' request method
*/
@@ -1176,6 +1181,70 @@ public class HttpRequest {
return post(encode ? encode(url) : url);
}
/**
* Start a 'PATCH' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest patch(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_PATCH);
}
/**
* Start a 'PATCH' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest patch(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_PATCH);
}
/**
* Start a 'PATCH' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* the query parameters to include as part of the baseUrl
* @param encode
* true to encode the full URL
*
* @see #append(CharSequence, Map)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest patch(final CharSequence baseUrl,
final Map<?, ?> params, final boolean encode) {
String url = append(baseUrl, params);
return patch(encode ? encode(url) : url);
}
/**
* Start a 'PATCH' request to the given URL along with the query params
*
* @param baseUrl
* @param encode
* true to encode the full URL
* @param params
* the name/value query parameter pairs to include as part of the
* baseUrl
*
* @see #append(CharSequence, Object...)
* @see #encode(CharSequence)
*
* @return request
*/
public static HttpRequest patch(final CharSequence baseUrl,
final boolean encode, final Object... params) {
String url = append(baseUrl, params);
return patch(encode ? encode(url) : url);
}
/**
* Start a 'PUT' request to the given URL
*

View File

@@ -25,26 +25,30 @@ abstract class CordovaHttp {
private static AtomicBoolean sslPinning = new AtomicBoolean(false);
private static AtomicBoolean acceptAllCerts = new AtomicBoolean(false);
private static AtomicBoolean validateDomainName = new AtomicBoolean(true);
private static AtomicBoolean disableRedirect = new AtomicBoolean(false);
private String urlString;
private JSONObject params;
private String serializerName;
private JSONObject headers;
private int timeoutInMilliseconds;
private CallbackContext callbackContext;
public CordovaHttp(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext) {
public CordovaHttp(String urlString, JSONObject params, JSONObject headers, int timeout, CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.serializerName = "default";
this.headers = headers;
this.timeoutInMilliseconds = timeout;
this.callbackContext = callbackContext;
}
public CordovaHttp(String urlString, JSONObject params, String serializerName, JSONObject headers, CallbackContext callbackContext) {
public CordovaHttp(String urlString, JSONObject params, String serializerName, JSONObject headers, int timeout, CallbackContext callbackContext) {
this.urlString = urlString;
this.params = params;
this.serializerName = serializerName;
this.headers = headers;
this.timeoutInMilliseconds = timeout;
this.callbackContext = callbackContext;
}
@@ -66,6 +70,10 @@ abstract class CordovaHttp {
validateDomainName.set(accept);
}
public static void disableRedirect(boolean disable) {
disableRedirect.set(disable);
}
protected String getUrlString() {
return this.urlString;
}
@@ -90,6 +98,10 @@ abstract class CordovaHttp {
return this.getStringMapFromJSONObject(this.headers);
}
protected int getRequestTimeout() {
return this.timeoutInMilliseconds;
}
protected CallbackContext getCallbackContext() {
return this.callbackContext;
}
@@ -107,6 +119,13 @@ abstract class CordovaHttp {
return request;
}
protected HttpRequest setupRedirect(HttpRequest request) {
if (disableRedirect.get()) {
request.followRedirects(false);
}
return request;
}
protected void respondWithError(int status, String msg) {
try {
JSONObject response = new JSONObject();

View File

@@ -3,6 +3,7 @@
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
@@ -16,8 +17,8 @@ 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, CallbackContext callbackContext) {
super(urlString, data, headers, callbackContext);
public CordovaHttpDelete(String urlString, JSONObject data, JSONObject headers, CallbackContext callbackContext, int timeout) {
super(urlString, data, headers, timeout, callbackContext);
}
@Override
@@ -25,9 +26,12 @@ class CordovaHttpDelete extends CordovaHttp implements Runnable {
try {
HttpRequest request = HttpRequest.delete(this.getUrlString(), this.getParamsMap(), false);
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
int code = request.code();
String body = request.body(CHARSET);
@@ -48,6 +52,8 @@ class CordovaHttpDelete extends CordovaHttp implements Runnable {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {

View File

@@ -7,6 +7,7 @@ import com.github.kevinsawicki.http.HttpRequest;
import com.github.kevinsawicki.http.HttpRequest.HttpRequestException;
import java.io.File;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -22,8 +23,8 @@ import org.json.JSONObject;
class CordovaHttpDownload extends CordovaHttp implements Runnable {
private String filePath;
public CordovaHttpDownload(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, String filePath) {
super(urlString, params, headers, callbackContext);
public CordovaHttpDownload(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, String filePath, int timeout) {
super(urlString, params, headers, timeout, callbackContext);
this.filePath = filePath;
}
@@ -31,9 +32,13 @@ class CordovaHttpDownload extends CordovaHttp implements Runnable {
public void run() {
try {
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParamsMap(), true);
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
int code = request.code();
JSONObject response = new JSONObject();
@@ -57,6 +62,8 @@ class CordovaHttpDownload extends CordovaHttp implements Runnable {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {

View File

@@ -3,6 +3,7 @@
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
@@ -16,8 +17,8 @@ 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, CallbackContext callbackContext) {
super(urlString, params, headers, callbackContext);
public CordovaHttpGet(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, int timeout) {
super(urlString, params, headers, timeout, callbackContext);
}
@Override
@@ -25,9 +26,12 @@ class CordovaHttpGet extends CordovaHttp implements Runnable {
try {
HttpRequest request = HttpRequest.get(this.getUrlString(), this.getParamsMap(), false);
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
int code = request.code();
String body = request.body(CHARSET);
@@ -48,6 +52,8 @@ class CordovaHttpGet extends CordovaHttp implements Runnable {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {

View File

@@ -3,6 +3,7 @@
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
@@ -15,8 +16,8 @@ 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, CallbackContext callbackContext) {
super(urlString, params, headers, callbackContext);
public CordovaHttpHead(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, int timeout) {
super(urlString, params, headers, timeout, callbackContext);
}
@Override
@@ -24,9 +25,12 @@ class CordovaHttpHead extends CordovaHttp implements Runnable {
try {
HttpRequest request = HttpRequest.head(this.getUrlString(), this.getParamsMap(), true);
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
int code = request.code();
JSONObject response = new JSONObject();
@@ -47,6 +51,8 @@ class CordovaHttpHead extends CordovaHttp implements Runnable {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {

View File

@@ -0,0 +1,70 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
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 CordovaHttpPatch extends CordovaHttp implements Runnable {
public CordovaHttpPatch(String urlString, JSONObject params, String serializerName, JSONObject headers, CallbackContext callbackContext, int timeout) {
super(urlString, params, serializerName, headers, timeout, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.patch(this.getUrlString());
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
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 SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {
this.respondWithError("There was an error with the request");
}
}
}
}

View File

@@ -39,14 +39,16 @@ public class CordovaHttpPlugin extends CordovaPlugin {
JSONObject params = args.getJSONObject(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
CordovaHttpPost post = new CordovaHttpPost(urlString, params, serializerName, headers, callbackContext);
int timeoutInMilliseconds = args.getInt(4) * 1000;
CordovaHttpPost post = new CordovaHttpPost(urlString, params, serializerName, headers, callbackContext, timeoutInMilliseconds);
cordova.getThreadPool().execute(post);
} else if (action.equals("get")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
CordovaHttpGet get = new CordovaHttpGet(urlString, params, headers, callbackContext);
int timeoutInMilliseconds = args.getInt(3) * 1000;
CordovaHttpGet get = new CordovaHttpGet(urlString, params, headers, callbackContext, timeoutInMilliseconds);
cordova.getThreadPool().execute(get);
} else if (action.equals("put")) {
@@ -54,21 +56,33 @@ public class CordovaHttpPlugin extends CordovaPlugin {
JSONObject params = args.getJSONObject(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
CordovaHttpPut put = new CordovaHttpPut(urlString, params, serializerName, headers, callbackContext);
int timeoutInMilliseconds = args.getInt(4) * 1000;
CordovaHttpPut put = new CordovaHttpPut(urlString, params, serializerName, headers, callbackContext, timeoutInMilliseconds);
cordova.getThreadPool().execute(put);
} else if (action.equals("delete")) {
} else if (action.equals("patch")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
String serializerName = args.getString(2);
JSONObject headers = args.getJSONObject(3);
CordovaHttpPatch patch = new CordovaHttpPatch(urlString, params, serializerName, headers, callbackContext);
cordova.getThreadPool().execute(patch);
}
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);
int timeoutInMilliseconds = args.getInt(3) * 1000;
CordovaHttpDelete delete = new CordovaHttpDelete(urlString, params, headers, callbackContext, timeoutInMilliseconds);
cordova.getThreadPool().execute(delete);
} else if (action.equals("head")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
CordovaHttpHead head = new CordovaHttpHead(urlString, params, headers, callbackContext);
int timeoutInMilliseconds = args.getInt(3) * 1000;
CordovaHttpHead head = new CordovaHttpHead(urlString, params, headers, callbackContext, timeoutInMilliseconds);
cordova.getThreadPool().execute(head);
} else if (action.equals("enableSSLPinning")) {
@@ -96,7 +110,8 @@ public class CordovaHttpPlugin extends CordovaPlugin {
JSONObject headers = args.getJSONObject(2);
String filePath = args.getString(3);
String name = args.getString(4);
CordovaHttpUpload upload = new CordovaHttpUpload(urlString, params, headers, callbackContext, filePath, name);
int timeoutInMilliseconds = args.getInt(5) * 1000;
CordovaHttpUpload upload = new CordovaHttpUpload(urlString, params, headers, callbackContext, filePath, name, timeoutInMilliseconds);
cordova.getThreadPool().execute(upload);
} else if (action.equals("downloadFile")) {
@@ -104,9 +119,14 @@ public class CordovaHttpPlugin extends CordovaPlugin {
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
String filePath = args.getString(3);
CordovaHttpDownload download = new CordovaHttpDownload(urlString, params, headers, callbackContext, filePath);
int timeoutInMilliseconds = args.getInt(4) * 1000;
CordovaHttpDownload download = new CordovaHttpDownload(urlString, params, headers, callbackContext, filePath, timeoutInMilliseconds);
cordova.getThreadPool().execute(download);
} else if (action.equals("disableRedirect")) {
boolean disable = args.getBoolean(0);
CordovaHttp.disableRedirect(disable);
callbackContext.success();
} else {
return false;
}

View File

@@ -3,6 +3,7 @@
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.cordova.CallbackContext;
@@ -15,8 +16,8 @@ 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);
public CordovaHttpPost(String urlString, JSONObject params, String serializerName, JSONObject headers, CallbackContext callbackContext, int timeout) {
super(urlString, params, serializerName, headers, timeout, callbackContext);
}
@Override
@@ -24,9 +25,12 @@ class CordovaHttpPost extends CordovaHttp implements Runnable {
try {
HttpRequest request = HttpRequest.post(this.getUrlString());
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
if (new String("json").equals(this.getSerializerName())) {
request.contentType(request.CONTENT_TYPE_JSON, request.CHARSET_UTF8);
@@ -51,9 +55,11 @@ class CordovaHttpPost 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) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {

View File

@@ -3,6 +3,7 @@
*/
package com.synconset.cordovahttp;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.apache.cordova.CallbackContext;
@@ -15,8 +16,8 @@ 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);
public CordovaHttpPut(String urlString, JSONObject data, String serializerName, JSONObject headers, CallbackContext callbackContext, int timeout) {
super(urlString, data, serializerName, headers, timeout, callbackContext);
}
@Override
@@ -24,9 +25,12 @@ class CordovaHttpPut extends CordovaHttp implements Runnable {
try {
HttpRequest request = HttpRequest.put(this.getUrlString());
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
if (new String("json").equals(this.getSerializerName())) {
request.contentType(request.CONTENT_TYPE_JSON, request.CHARSET_UTF8);
@@ -54,6 +58,8 @@ class CordovaHttpPut extends CordovaHttp implements Runnable {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {

View File

@@ -5,6 +5,7 @@ package com.synconset.cordovahttp;
import java.io.File;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -29,8 +30,8 @@ class CordovaHttpUpload extends CordovaHttp implements Runnable {
private String filePath;
private String name;
public CordovaHttpUpload(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, String filePath, String name) {
super(urlString, params, headers, callbackContext);
public CordovaHttpUpload(String urlString, JSONObject params, JSONObject headers, CallbackContext callbackContext, String filePath, String name, int timeout) {
super(urlString, params, headers, timeout, callbackContext);
this.filePath = filePath;
this.name = name;
}
@@ -40,9 +41,12 @@ class CordovaHttpUpload extends CordovaHttp implements Runnable {
try {
HttpRequest request = HttpRequest.post(this.getUrlString());
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
request.uncompress(true);
URI uri = new URI(filePath);
@@ -96,6 +100,8 @@ class CordovaHttpUpload extends CordovaHttp implements Runnable {
} catch (HttpRequestException e) {
if (e.getCause() instanceof UnknownHostException) {
this.respondWithError(0, "The host could not be resolved");
} else if (e.getCause() instanceof SocketTimeoutException) {
this.respondWithError(1, "The request timed out");
} else if (e.getCause() instanceof SSLHandshakeException) {
this.respondWithError("SSL handshake failed");
} else {

View File

@@ -7,9 +7,11 @@
- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command;
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command;
- (void)validateDomainName:(CDVInvokedUrlCommand*)command;
- (void)disableRedirect:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;
- (void)put:(CDVInvokedUrlCommand*)command;
- (void)patch:(CDVInvokedUrlCommand*)command;
- (void)delete:(CDVInvokedUrlCommand*)command;
- (void)uploadFile:(CDVInvokedUrlCommand*)command;
- (void)downloadFile:(CDVInvokedUrlCommand*)command;

View File

@@ -6,25 +6,31 @@
@interface CordovaHttpPlugin()
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager;
- (void)setResults:(NSMutableDictionary*)dictionary withTask:(NSURLSessionTask*)task;
- (void)handleSuccess:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response andData:(id)data;
- (void)handleError:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response error:(NSError*)error;
- (NSNumber*)getStatusCode:(NSError*) error;
- (NSMutableDictionary*)copyHeaderFields:(NSDictionary*)headerFields;
- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager;
- (void)setRedirect:(AFHTTPSessionManager*)manager;
@end
@implementation CordovaHttpPlugin {
AFSecurityPolicy *securityPolicy;
bool redirect;
}
- (void)pluginInitialize {
securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
redirect = true;
}
- (void)setRequestSerializer:(NSString*)serializerName forManager:(AFHTTPSessionManager*)manager {
if ([serializerName isEqualToString:@"json"]) {
manager.requestSerializer = [AFJSONRequestSerializer serializer];
} else {
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
}
if ([serializerName isEqualToString:@"json"]) {
manager.requestSerializer = [AFJSONRequestSerializer serializer];
} else {
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
}
}
- (void)setRequestHeaders:(NSDictionary*)headers forManager:(AFHTTPSessionManager*)manager {
@@ -33,12 +39,71 @@
}];
}
- (void)setResults:(NSMutableDictionary*)dictionary withTask:(NSURLSessionTask*)task {
if (task.response != nil) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
- (void)setRedirect:(AFHTTPSessionManager*)manager {
[manager setTaskWillPerformHTTPRedirectionBlock:^NSURLRequest * _Nonnull(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSURLResponse * _Nonnull response, NSURLRequest * _Nonnull request) {
if (redirect) {
return request;
} else {
return nil;
}
}];
}
- (void)handleSuccess:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response andData:(id)data {
if (response != nil) {
[dictionary setObject:[NSNumber numberWithInt:response.statusCode] forKey:@"status"];
[dictionary setObject:response.allHeaderFields forKey:@"headers"];
[dictionary setObject:[self copyHeaderFields:response.allHeaderFields] forKey:@"headers"];
}
if (data != nil) {
[dictionary setObject:data forKey:@"data"];
}
}
- (void)handleError:(NSMutableDictionary*)dictionary withResponse:(NSHTTPURLResponse*)response error:(NSError*)error {
if (response != nil) {
[dictionary setObject:[NSNumber numberWithInt:response.statusCode] forKey:@"status"];
[dictionary setObject:[self copyHeaderFields:response.allHeaderFields] forKey:@"headers"];
[dictionary setObject:[[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding] forKey:@"error"];
} else {
[dictionary setObject:[self getStatusCode:error] forKey:@"status"];
[dictionary setObject:[error localizedDescription] forKey:@"error"];
}
}
- (NSNumber*)getStatusCode:(NSError*) error {
switch ([error code]) {
case -1001:
// timeout
return [NSNumber numberWithInt:1];
case -1002:
// unsupported URL
return [NSNumber numberWithInt:2];
case -1003:
// server not found
return [NSNumber numberWithInt:0];
case -1009:
// no connection
return [NSNumber numberWithInt:3];
default:
return [NSNumber numberWithInt:-1];
}
}
- (NSMutableDictionary*)copyHeaderFields:(NSDictionary *)headerFields {
NSMutableDictionary *headerFieldsCopy = [[NSMutableDictionary alloc] initWithCapacity:headerFields.count];
NSString *headerKeyCopy;
for (NSString *headerKey in headerFields.allKeys) {
headerKeyCopy = [[headerKey mutableCopy] lowercaseString];
[headerFieldsCopy setValue:[headerFields objectForKey:headerKey] forKey:headerKeyCopy];
}
return headerFieldsCopy;
}
- (void)setTimeout:(NSTimeInterval)timeout forManager:(AFHTTPSessionManager*)manager {
[manager.requestSerializer setTimeoutInterval:timeout];
}
- (void)enableSSLPinning:(CDVInvokedUrlCommand*)command {
@@ -53,6 +118,16 @@
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)disableRedirect:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil;
bool disable = [[command.arguments objectAtIndex:0] boolValue];
redirect = !disable;
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (void)acceptAllCerts:(CDVInvokedUrlCommand*)command {
CDVPluginResult* pluginResult = nil;
bool allow = [[command.arguments objectAtIndex:0] boolValue];
@@ -76,26 +151,30 @@
- (void)post:(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];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
[self setRequestSerializer: serializerName forManager: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[dictionary setObject:responseObject forKey:@"data"];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
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"];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
@@ -104,26 +183,31 @@
- (void)get:(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];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:3] doubleValue];
[self setRequestSerializer: @"default" forManager: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager GET:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[dictionary setObject:responseObject forKey:@"data"];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
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"];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
@@ -132,26 +216,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];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
[self setRequestSerializer: serializerName forManager: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: 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"];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
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"];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
- (void)patch:(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];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
[self setRequestSerializer: serializerName forManager: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager PATCH:url parameters:parameters success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
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 handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
@@ -160,26 +280,30 @@
- (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];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:3] doubleValue];
[self setRequestSerializer: @"default" forManager: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: 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"];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:responseObject];
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"];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
@@ -191,22 +315,26 @@
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:3] doubleValue];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager HEAD:url parameters:parameters success:^(NSURLSessionTask *task) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
// no 'body' for HEAD request, omitting 'data'
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:nil];
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"];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
@@ -215,15 +343,19 @@
- (void)uploadFile:(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];
NSString *filePath = [command.arguments objectAtIndex: 3];
NSString *name = [command.arguments objectAtIndex: 4];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:5] doubleValue];
NSURL *fileURL = [NSURL URLWithString: filePath];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
@@ -240,14 +372,14 @@
}
} progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:nil];
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"];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
@@ -257,12 +389,16 @@
- (void)downloadFile:(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];
NSString *filePath = [command.arguments objectAtIndex: 3];
NSTimeInterval timeoutInSeconds = [[command.arguments objectAtIndex:4] doubleValue];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
if ([filePath hasPrefix:@"file://"]) {
filePath = [filePath substringFromIndex:7];
@@ -292,7 +428,7 @@
*
* Modified by Andrew Stephan for Sync OnSet
*
*/
*/
// Download response is okay; begin streaming output to file
NSString* parentPath = [filePath stringByDeletingLastPathComponent];
@@ -322,15 +458,15 @@
id filePlugin = [self.commandDelegate getCommandInstance:@"File"];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[self handleSuccess:dictionary withResponse:(NSHTTPURLResponse*)task.response andData:nil];
[dictionary setObject:[filePlugin getDirectoryEntry:filePath isDirectory:NO] forKey:@"file"];
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"];
[self handleError:dictionary withResponse:(NSHTTPURLResponse*)task.response error:error];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];

View File

@@ -128,6 +128,7 @@ var http = {
headers: {},
dataSerializer: 'urlencoded',
sslPinning: false,
timeoutInSeconds: 60.0,
getBasicAuthHeader: function (username, password) {
return {'Authorization': 'Basic ' + b64EncodeUnicode(username + ':' + password)};
},
@@ -143,12 +144,21 @@ var http = {
clearCookies: function () {
return cookieHandler.clearCookies();
},
removeCookies: function (url, callback) {
cookieHandler.removeCookies(url, callback);
},
setRequestTimeout: function(timeout) {
this.timeoutInSeconds = timeout;
},
enableSSLPinning: function (enable, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'enableSSLPinning', [enable]);
},
acceptAllCerts: function (allow, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'acceptAllCerts', [allow]);
},
disableRedirect: function(disable, success, failure) {
return exec(success, failure, "CordovaHttpPlugin", "disableRedirect", [disable]);
},
validateDomainName: function (validate, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'validateDomainName', [validate]);
},
@@ -163,7 +173,7 @@ var http = {
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'post', [url, data, this.dataSerializer, headers]);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'post', [url, data, this.dataSerializer, headers, this.timeoutInSeconds]);
},
get: function (url, params, headers, success, failure) {
handleMissingCallbacks(success, failure);
@@ -176,7 +186,7 @@ var http = {
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'get', [url, params, headers]);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'get', [url, params, headers, this.timeoutInSeconds]);
},
put: function (url, data, headers, success, failure) {
handleMissingCallbacks(success, failure);
@@ -189,8 +199,23 @@ var http = {
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'put', [url, data, this.dataSerializer, headers]);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'put', [url, data, this.dataSerializer, headers, this.timeoutInSeconds]);
},
patch: function (url, data, headers, success, failure) {
handleMissingCallbacks(success, failure);
data = data || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
headers = mergeHeaders(getCookieHeader(url), headers);
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'patch', [url, data, this.dataSerializer, headers, this.timeoutInSeconds]);
},
delete: function (url, params, headers, success, failure) {
handleMissingCallbacks(success, failure);
@@ -202,7 +227,7 @@ var http = {
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'delete', [url, params, headers]);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'delete', [url, params, headers, this.timeoutInSeconds]);
},
head: function (url, params, headers, success, failure) {
handleMissingCallbacks(success, failure);
@@ -215,7 +240,7 @@ var http = {
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'head', [url, params, headers]);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'head', [url, params, headers, this.timeoutInSeconds]);
},
uploadFile: function (url, params, headers, filePath, name, success, failure) {
handleMissingCallbacks(success, failure);
@@ -228,7 +253,7 @@ var http = {
var onSuccess = injectCookieHandler(url, success);
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFile', [url, params, headers, filePath, name]);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'uploadFile', [url, params, headers, filePath, name, this.timeoutInSeconds]);
},
downloadFile: function (url, params, headers, filePath, success, failure) {
handleMissingCallbacks(success, failure);
@@ -241,7 +266,7 @@ var http = {
var onSuccess = injectCookieHandler(url, injectFileEntryHandler(success));
var onFail = injectCookieHandler(url, failure);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'downloadFile', [url, params, headers, filePath]);
return exec(onSuccess, onFail, 'CordovaHttpPlugin', 'downloadFile', [url, params, headers, filePath, this.timeoutInSeconds]);
}
};

View File

@@ -42,17 +42,26 @@ function registerService(http) {
return http.setHeader(header, value);
},
setDataSerializer: function (serializer) {
return http.setParamSerializer(serializer);
return http.setDataSerializer(serializer);
},
clearCookies: function () {
return http.clearCookies();
},
removeCookies: function (url) {
return http.removeCookies(url);
},
setRequestTimeout: function (timeout) {
return http.setRequestTimeout(timeout);
},
enableSSLPinning: function (enable) {
return makePromise(http.enableSSLPinning, [enable]);
},
acceptAllCerts: function (allow) {
return makePromise(http.acceptAllCerts, [allow]);
},
disableRedirect: function(disable) {
return makePromise(http.disableRedirect, [disable]);
},
validateDomainName: function (validate) {
return makePromise(http.validateDomainName, [validate]);
},

View File

@@ -11,7 +11,8 @@ var cookieJar = new ToughCookie.CookieJar(store);
module.exports = {
setCookieFromString: setCookieFromString,
getCookieString: getCookieString,
clearCookies: clearCookies
clearCookies: clearCookies,
removeCookies: removeCookies
}
function splitCookieString(cookieStr) {
@@ -20,7 +21,7 @@ function splitCookieString(cookieStr) {
var processedCookie = null;
for (var i = 0; i < cookieParts.length; ++i) {
if (cookieParts[i].substr(-11, 8) === 'expires=') {
if (cookieParts[i].substr(-11, 8).toLowerCase() === 'expires=') {
processedCookie = cookieParts[i] + ',' + cookieParts[i + 1];
i++;
} else {
@@ -51,3 +52,15 @@ function getCookieString(url) {
function clearCookies() {
window.localStorage.removeItem(storeKey);
}
function removeCookies(url, cb) {
cookieJar.getCookies(url, function(error, cookies) {
if (!cookies || cookies.length === 0) {
return cb(null, []);
}
var domain = cookies[0].domain;
cookieJar.store.removeCookies(domain, null, cb);
});
}

4851
www/umd-tough-cookie.js Normal file

File diff suppressed because one or more lines are too long