Merge branch 'feature-put-delete-methods'

This commit is contained in:
Sefa Ilkimen
2016-11-14 15:13:55 +01:00
8 changed files with 276 additions and 53 deletions
+23 -13
View File
@@ -6,6 +6,7 @@ Cordova / Phonegap plugin for communicating with HTTP servers. Supports iOS and
## Advantages over Javascript requests
- 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).
## Updates
@@ -23,7 +24,11 @@ using the Cordova / Phonegap command line interface.
## 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.
@@ -31,12 +36,8 @@ This plugin creates a cordovaHTTP service inside of a cordovaHTTP module. You m
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
## Sync Functions
## Synchronous Functions
### getBasicAuthHeader
This returns an object representing a basic HTTP Authorization header of the form `{'Authorization': 'Basic base64encodedusernameandpassword'}`
@@ -53,16 +54,19 @@ Set a header for all future requests. Takes a header and a value.
cordovaHTTP.setHeader("Header", "Value");
### setParamSerializer
Set the parameter serializer which will be used for all future POST and PUT requests. Takes a string representing the name of the serializer.
### 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.setParamSerializer("urlencoded");
cordovaHTTP.setDataSerializer("urlencoded");
You can choose one of these two:
* `urlencoded`: send parameters as url encoded content in body (content type "application/x-www-form-urlencoded")
* `json`: send parameters as JSON encoded content in body (content type "application/json")
* `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")
## Async Functions
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.
### enableSSLPinning
@@ -97,7 +101,7 @@ Whether or not to validate the domain name in the certificate. This defaults to
});
### 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
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:
@@ -157,6 +161,12 @@ Execute a GET request. Takes a URL, parameters, and headers. See the [post](#p
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
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.
+13 -11
View File
@@ -4,20 +4,20 @@
id="cordova-plugin-advanced-http"
version="1.3.0">
<name>SSL Pinning</name>
<name>Advanced HTTP plugin</name>
<description>
Cordova / Phonegap plugin for communicating with HTTP servers using SSL pinning
</description>
<engines>
<engine name="cordova" version=">=3.0.0" />
<engine name="cordova" version=">=3.5.0" />
</engines>
<dependency id="cordova-plugin-file" version=">=2.0.0" />
<js-module src="www/cordovaHTTP.js" name="CordovaHttpPlugin">
<clobbers target="CordovaHttpPlugin" />
<js-module src="www/cordovaHttp.js" name="http">
<clobbers target="cordova.plugin.http" />
</js-module>
<!-- ios -->
@@ -70,14 +70,16 @@
<uses-permission android:name="android.permission.INTERNET" />
</config-file>
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttp.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpGet.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/CordovaHttpHead.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpUpload.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpDownload.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpPlugin.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/github/kevinsawicki/http/HttpRequest.java" target-dir="src/com/github/kevinsawicki/http" />
<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/CordovaHttp.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpDelete.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpDownload.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpGet.java" target-dir="src/com/synconset/cordovahttp" />
<source-file src="src/android/com/synconset/cordovahttp/CordovaHttpHead.java" target-dir="src/com/synconset/cordovahttp" />
<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/CordovaHttpUpload.java" target-dir="src/com/synconset/cordovahttp" />
</platform>
</plugin>
@@ -0,0 +1,58 @@
/**
* A HTTP plugin for Cordova / Phonegap
*/
package com.synconset.cordovahttp;
import java.net.UnknownHostException;
import javax.net.ssl.SSLHandshakeException;
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.HttpRequestException;
class CordovaHttpDelete extends CordovaHttp implements Runnable {
public CordovaHttpDelete(String urlString, JSONObject data, JSONObject headers, CallbackContext callbackContext) {
super(urlString, data, headers, callbackContext);
}
@Override
public void run() {
try {
HttpRequest request = HttpRequest.delete(this.getUrlString(), this.getParamsMap(), false);
this.setupSecurity(request);
request.acceptCharset(CHARSET);
request.headers(this.getHeadersMap());
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");
}
}
}
}
@@ -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");
}
}
}
}
@@ -34,21 +34,7 @@ public class CordovaHttpPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
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);
cordova.getThreadPool().execute(get);
} 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);
cordova.getThreadPool().execute(head);
} else if (action.equals("post")) {
if (action.equals("post")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
String serializerName = args.getString(2);
@@ -56,6 +42,35 @@ public class CordovaHttpPlugin extends CordovaPlugin {
CordovaHttpPost post = new CordovaHttpPost(urlString, params, serializerName, headers, callbackContext);
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);
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")) {
String urlString = args.getString(0);
JSONObject params = args.getJSONObject(1);
JSONObject headers = args.getJSONObject(2);
CordovaHttpHead head = new CordovaHttpHead(urlString, params, headers, callbackContext);
cordova.getThreadPool().execute(head);
} else if (action.equals("enableSSLPinning")) {
try {
boolean enable = args.getBoolean(0);
+3 -1
View File
@@ -9,7 +9,9 @@
- (void)validateDomainName:(CDVInvokedUrlCommand*)command;
- (void)post:(CDVInvokedUrlCommand*)command;
- (void)get:(CDVInvokedUrlCommand*)command;
- (void)put:(CDVInvokedUrlCommand*)command;
- (void)delete:(CDVInvokedUrlCommand*)command;
- (void)uploadFile:(CDVInvokedUrlCommand*)command;
- (void)downloadFile:(CDVInvokedUrlCommand*)command;
@end
@end
+56
View File
@@ -129,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 {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
+29 -13
View File
@@ -64,7 +64,7 @@ function checkSerializer(serializer) {
var http = {
headers: {},
paramSerializer: 'urlencoded',
dataSerializer: 'urlencoded',
sslPinning: false,
getBasicAuthHeader: function (username, password) {
return {'Authorization': 'Basic ' + b64EncodeUnicode(username + ':' + password)};
@@ -75,8 +75,8 @@ var http = {
setHeader: function (header, value) {
this.headers[header] = value;
},
setParamSerializer: function (serializer) {
this.paramSerializer = checkSerializer(serializer);
setDataSerializer: function (serializer) {
this.dataSerializer = checkSerializer(serializer);
},
enableSSLPinning: function (enable, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'enableSSLPinning', [enable]);
@@ -87,11 +87,11 @@ var http = {
validateDomainName: function (validate, success, failure) {
return exec(success, failure, 'CordovaHttpPlugin', 'validateDomainName', [validate]);
},
post: function (url, params, headers, success, failure) {
params = params || {};
post: function (url, data, headers, success, failure) {
data = data || {};
headers = headers || {};
headers = mergeHeaders(this.headers, headers);
return exec(success, failure, 'CordovaHttpPlugin', 'post', [url, params, this.paramSerializer, headers]);
return exec(success, failure, 'CordovaHttpPlugin', 'post', [url, data, this.dataSerializer, headers]);
},
get: function (url, params, headers, success, failure) {
params = params || {};
@@ -99,6 +99,18 @@ var http = {
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]);
@@ -123,8 +135,6 @@ var http = {
}
};
module.exports = http;
if (typeof angular !== 'undefined') {
angular.module('cordovaHTTP', []).factory('cordovaHTTP', function ($timeout, $q) {
function makePromise(fn, args, async) {
@@ -166,7 +176,7 @@ if (typeof angular !== 'undefined') {
setHeader: function (header, value) {
return http.setHeader(header, value);
},
setParamSerializer: function (serializer) {
setDataSerializer: function (serializer) {
return http.setParamSerializer(serializer);
},
enableSSLPinning: function (enable) {
@@ -178,12 +188,18 @@ if (typeof angular !== 'undefined') {
validateDomainName: function (validate) {
return makePromise(http.validateDomainName, [validate]);
},
post: function (url, params, headers) {
return makePromise(http.post, [url, params, headers], true);
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);
},
@@ -196,6 +212,6 @@ if (typeof angular !== 'undefined') {
};
return cordovaHTTP;
});
} else {
window.cordovaHTTP = http;
}
module.exports = http;