Compare commits

..
11 Commits
23 changed files with 5139 additions and 7 deletions
-1
View File
@@ -1,5 +1,4 @@
node_modules/**
tags
.zedstate
/www/umd-tough-cookie.js
/temp
+7 -1
View File
@@ -1,6 +1,12 @@
# Changelog
## v.1.5.10
## 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)
+5
View File
@@ -56,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.
+2 -4
View File
@@ -1,11 +1,9 @@
{
"name": "cordova-plugin-advanced-http",
"version": "1.5.10",
"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": "npm run build && ./scripts/test-installation.sh"
"test": "./scripts/test-installation.sh"
},
"cordova": {
"id": "cordova-plugin-advanced-http",
+1
View File
@@ -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>
Executable
+8
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"
+8
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
@@ -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
*
@@ -25,6 +25,7 @@ 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;
@@ -69,6 +70,10 @@ abstract class CordovaHttp {
validateDomainName.set(accept);
}
public static void disableRedirect(boolean disable) {
disableRedirect.set(disable);
}
protected String getUrlString() {
return this.urlString;
}
@@ -114,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();
@@ -27,6 +27,7 @@ class CordovaHttpDelete extends CordovaHttp implements Runnable {
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());
@@ -34,6 +34,7 @@ class CordovaHttpDownload extends CordovaHttp implements Runnable {
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());
@@ -27,6 +27,7 @@ class CordovaHttpGet extends CordovaHttp implements Runnable {
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());
@@ -26,6 +26,7 @@ class CordovaHttpHead extends CordovaHttp implements Runnable {
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());
@@ -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");
}
}
}
}
@@ -60,7 +60,16 @@ public class CordovaHttpPlugin extends CordovaPlugin {
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);
@@ -114,6 +123,10 @@ public class CordovaHttpPlugin extends CordovaPlugin {
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;
}
@@ -26,6 +26,7 @@ class CordovaHttpPost extends CordovaHttp implements Runnable {
HttpRequest request = HttpRequest.post(this.getUrlString());
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
@@ -26,6 +26,7 @@ class CordovaHttpPut extends CordovaHttp implements Runnable {
HttpRequest request = HttpRequest.put(this.getUrlString());
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
@@ -42,6 +42,7 @@ class CordovaHttpUpload extends CordovaHttp implements Runnable {
HttpRequest request = HttpRequest.post(this.getUrlString());
request.readTimeout(this.getRequestTimeout());
this.setupRedirect(request);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
+2
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;
+62
View File
@@ -11,15 +11,18 @@
- (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 {
@@ -36,6 +39,16 @@
}];
}
- (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"];
@@ -105,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];
@@ -138,6 +161,7 @@
[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];
@@ -169,6 +193,7 @@
[self setRequestSerializer: @"default" forManager: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
@@ -201,6 +226,7 @@
[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];
@@ -219,6 +245,38 @@
}];
}
- (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];
}];
}
- (void)delete:(CDVInvokedUrlCommand*)command {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
@@ -231,6 +289,7 @@
[self setRequestSerializer: @"default" forManager: manager];
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
@@ -260,6 +319,7 @@
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
@@ -295,6 +355,7 @@
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
@@ -337,6 +398,7 @@
[self setRequestHeaders: headers forManager: manager];
[self setTimeout:timeoutInSeconds forManager:manager];
[self setRedirect: manager];
if ([filePath hasPrefix:@"file://"]) {
filePath = [filePath substringFromIndex:7];
+18
View File
@@ -156,6 +156,9 @@ var http = {
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]);
},
@@ -198,6 +201,21 @@ var http = {
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);
+3
View File
@@ -59,6 +59,9 @@ function registerService(http) {
acceptAllCerts: function (allow) {
return makePromise(http.acceptAllCerts, [allow]);
},
disableRedirect: function(disable) {
return makePromise(http.disableRedirect, [disable]);
},
validateDomainName: function (validate) {
return makePromise(http.validateDomainName, [validate]);
},
File diff suppressed because one or more lines are too long