Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: HTTP API #2495

Closed
wants to merge 29 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
5309016
iOS GET and POST works for json
mlynch Feb 26, 2020
4bcc2b9
HTTP
mlynch Feb 26, 2020
eaef1c6
Fix head
mlynch Feb 29, 2020
4c4d361
application/x-www-form-urlencoded support
mlynch Feb 29, 2020
a5d534f
Support setting and getting cookies for URLs
mlynch Feb 29, 2020
ba67fdf
Working on download
mlynch Feb 29, 2020
8250dd9
Downloads working
mlynch Feb 29, 2020
aafe6e9
Working on upload
mlynch Mar 1, 2020
f023d60
Uploads working
mlynch Mar 1, 2020
d05dc99
Starting Android and mroe cookie methods and headers
mlynch Mar 2, 2020
13cb9fd
Android
mlynch Mar 2, 2020
ea768ac
Android cookie routines
mlynch Mar 14, 2020
2cd077f
Http cookies
mlynch Mar 14, 2020
ffdfe35
Response and headers for Android
mlynch Mar 14, 2020
b32b979
Post JSON on Android
mlynch Mar 19, 2020
178df14
Android post urlencoded form data
mlynch Mar 19, 2020
9e06d7b
Download sort of working on android
mlynch Mar 19, 2020
e879dca
Uploads at least working on Android
mlynch Mar 19, 2020
3d32312
Clean up android and multipart post
mlynch Mar 20, 2020
0eb6dcc
Properly handle android download permissions
mlynch Mar 20, 2020
965700e
Manage perms for uploading files
mlynch Mar 20, 2020
7afc93d
Cookies are set
mlynch Mar 20, 2020
961709a
Fix directory support for iOS downloads
mlynch Mar 20, 2020
7de9173
Download location on Android
mlynch Mar 20, 2020
63128f2
Starting web implementation
mlynch Mar 20, 2020
84b0ad0
Add cookies support to web
mlynch Apr 2, 2020
6e7bb49
Set and remove cookies
mlynch Apr 2, 2020
7afcde6
Web api for downloads and uploads
mlynch Apr 3, 2020
ae81f32
Missing server.js
mlynch Apr 15, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions core/src/core-plugin-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface PluginRegistry {
Filesystem: FilesystemPlugin;
Geolocation: GeolocationPlugin;
Haptics: HapticsPlugin;
Http: HttpPlugin;
Keyboard: KeyboardPlugin;
LocalNotifications: LocalNotificationsPlugin;
Modals: ModalsPlugin;
Expand Down Expand Up @@ -904,6 +905,36 @@ export enum HapticsNotificationType {
ERROR = 'ERROR'
}

// Http

export interface HttpPlugin {
request(options: HttpOptions): Promise<HttpResponse>;
}

export interface HttpOptions {
url: string;
method: string;
params?: HttpParams;
data?: any;
headers?: HttpHeaders;
}

export interface HttpParams {
[key:string]: string;
}

export interface HttpHeaders {
[key:string]: string;
}

export interface HttpResponse {
data: any;
status: number;
headers: HttpHeaders;
}

// Vibrate

export interface VibrateOptions {
duration?: number;
}
Expand Down
3 changes: 3 additions & 0 deletions example/android/app/src/main/assets/capacitor.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
"plugins": {
"SplashScreen": {
"launchShowDuration": 12345
},
"LocalNotifications": {
"smallIcon": "ic_stat_icon_config_sample"
}
}
}
3 changes: 2 additions & 1 deletion example/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { Plugins } from '@capacitor/core';
export class MyApp {
@ViewChild(Nav) nav: Nav;

rootPage = 'AppPage';
rootPage = 'HttpPage';

PLUGINS = [
{ name: 'App', page: 'AppPage' },
Expand All @@ -22,6 +22,7 @@ export class MyApp {
{ name: 'Filesystem', page: 'FilesystemPage' },
{ name: 'Geolocation', page: 'GeolocationPage' },
{ name: 'Haptics', page: 'HapticsPage' },
{ name: 'Http', page: 'HttpPage' },
{ name: 'Keyboard', page: 'KeyboardPage' },
{ name: 'LocalNotifications', page: 'LocalNotificationsPage' },
{ name: 'Modals', page: 'ModalsPage' },
Expand Down
26 changes: 26 additions & 0 deletions example/src/pages/http/http.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!--
Generated template for the KeyboardPage page.

See http://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
-->
<ion-header>

<ion-navbar>
<ion-title>Http</ion-title>
</ion-navbar>

</ion-header>


<ion-content padding no-bounce>
<button (click)="get()" ion-button>GET</button>
<button (click)="head()" ion-button>HEAD</button>
mlynch marked this conversation as resolved.
Show resolved Hide resolved
<button (click)="delete()" ion-button>DELETE</button>
<button (click)="patch()" ion-button>PATCH</button>
<button (click)="post()" ion-button>POST</button>
<button (click)="put()" ion-button>PUT</button>

<h4>Output</h4>
<ion-textarea [value]="output" placeholder="Ouput"></ion-textarea>
</ion-content>
13 changes: 13 additions & 0 deletions example/src/pages/http/http.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { HttpPage } from './http';

@NgModule({
declarations: [
HttpPage,
],
imports: [
IonicPageModule.forChild(HttpPage),
],
})
export class HttpPageModule { }
6 changes: 6 additions & 0 deletions example/src/pages/http/http.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
ion-textarea {
border: 1px solid #eee;
textarea {
height: 500px;
}
}
72 changes: 72 additions & 0 deletions example/src/pages/http/http.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, LoadingController, Loading } from 'ionic-angular';

import { Plugins } from '@capacitor/core';

/**
* Generated class for the KeyboardPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/

@IonicPage()
@Component({
selector: 'page-http',
templateUrl: 'http.html',
})
export class HttpPage {
url: string = 'https://jsonplaceholder.typicode.com';
output: string = '';

loading: Loading;

constructor(public navCtrl: NavController, public navParams: NavParams, public loadingCtrl: LoadingController) {
}

ionViewDidLoad() {
console.log('ionViewDidLoad KeyboardPage');
}

async get() {
this.output = '';

this.loading = this.loadingCtrl.create({
content: 'Requesting...'
});
this.loading.present();
const ret = await Plugins.Http.request({
method: 'GET',
url: `${this.url}/posts/1`
});
console.log('Got ret', ret);
this.loading.dismiss();

this.output = JSON.stringify(ret, null, 2);
}

delete = () => this.mutate('/posts/1', 'DELETE', { title: 'foo', body: 'bar', userId: 1 });
patch = () => this.mutate('/posts/1', 'PATCH', { title: 'foo', body: 'bar', userId: 1 });
post = () => this.mutate('/posts', 'POST', { title: 'foo', body: 'bar', userId: 1 });
put = () => this.mutate('/posts/1', 'PUT', { title: 'foo', body: 'bar', userId: 1 });

async mutate(path, method, data = {}) {
this.output = '';
this.loading = this.loadingCtrl.create({
content: 'Requesting...'
});
this.loading.present();
const ret = await Plugins.Http.request({
url: `${this.url}${path}`,
method: method,
headers: {
'content-type': 'application/json'
},
data
});
console.log('Got ret', ret);
this.loading.dismiss();
this.output = JSON.stringify(ret, null, 2);
}

}
4 changes: 4 additions & 0 deletions ios/Capacitor/Capacitor/Plugins/DefaultPlugins.m
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@
CAP_PLUGIN_METHOD(vibrate, CAPPluginReturnNone);
)

CAP_PLUGIN(CAPHttpPlugin, "Http",
CAP_PLUGIN_METHOD(request, CAPPluginReturnPromise);
)

CAP_PLUGIN(CAPKeyboard, "Keyboard",
CAP_PLUGIN_METHOD(show, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(hide, CAPPluginReturnPromise);
Expand Down
140 changes: 140 additions & 0 deletions ios/Capacitor/Capacitor/Plugins/Http.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import Foundation
import AudioToolbox

@objc(CAPHttpPlugin)
public class CAPHttpPlugin: CAPPlugin {

@objc public func request(_ call: CAPPluginCall) {
guard let urlValue = call.getString("url") else {
return call.reject("Must provide a URL")
}
guard let method = call.getString("method") else {
return call.reject("Must provide a method. One of GET, DELETE, HEAD PATCH, POST, or PUT")
}

guard let url = URL(string: urlValue) else {
return call.reject("Invalid URL")
}

switch method {
case "GET", "HEAD":
get(call, url, method)
case "DELETE", "PATCH", "POST", "PUT":
mutate(call, url, method)
default:
call.reject("Unknown method")
}
}

// Handle GET operations
func get(_ call: CAPPluginCall, _ url: URL, _ method: String) {
var request = URLRequest(url: url)
request.httpMethod = method
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print("Error on GET", data, response, error)
call.reject("Error", error, [:])
return
}

let res = response as! HTTPURLResponse

call.resolve(self.buildResponse(data, res))
}

task.resume()
}

// Handle mutation operations: DELETE, PATCH, POST, and PUT
func mutate(_ call: CAPPluginCall, _ url: URL, _ method: String) {
let data = call.getObject("data")

var request = URLRequest(url: url)
request.httpMethod = method

let headers = (call.getObject("headers") ?? [:]) as [String:Any]

let contentType = getRequestHeader(headers, "Content-Type") as? String

if data != nil && contentType != nil {
do {
try setRequestData(request, data!, contentType!)
} catch let e {
call.reject("Unable to set request data", e)
return
}
}

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print("Error on mutate ", data, response, error)
call.reject("Error", error, [:])
return
}

let res = response as! HTTPURLResponse

call.resolve(self.buildResponse(data, res))
}

task.resume()
}

func buildResponse(_ data: Data?, _ response: HTTPURLResponse) -> [String:Any] {

var ret = [:] as [String:Any]

ret["status"] = response.statusCode
ret["headers"] = response.allHeaderFields

let contentType = response.allHeaderFields["Content-Type"] as? String

if data != nil && contentType != nil && contentType!.contains("application/json") {
if let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any] {
print("Got json")
print(json)
// handle json...
ret["data"] = json
}
}
// TODO: Handle other response content types, including binary
/*
else {
ret["data"] =
}*/

return ret
}

func getRequestHeader(_ headers: [String:Any], _ header: String) -> Any? {
var normalizedHeaders = [:] as [String:Any]
headers.keys.forEach { (key) in
normalizedHeaders[key.lowercased()] = headers[key]
}
return normalizedHeaders[header.lowercased()]
}

func setRequestData(_ request: URLRequest, _ data: [String:Any], _ contentType: String) throws {
if contentType.contains("application/json") {
try setRequestDataJson(request, data)
} else if contentType.contains("application/x-www-form-urlencoded") {
setRequestDataFormUrlEncoded(request, data)
} else if contentType.contains("multipart/form-data") {
setRequestDataMultipartFormData(request, data)
}
}

func setRequestDataJson(_ request: URLRequest, _ data: [String:Any]) throws {
var req = request
let jsonData = try JSONSerialization.data(withJSONObject: data)
req.httpBody = jsonData
}

func setRequestDataFormUrlEncoded(_ request: URLRequest, _ data: [String:Any]) {

}

func setRequestDataMultipartFormData(_ request: URLRequest, _ data: [String:Any]) {

}
}