In this tutorial, we will learn how to make HTTP calls using Ionic’s Native HTTP plugin.
Making Native server calls over provides advantages over traditional JavaScript HTTP calls. Native HTTP calls are made in Android and IOS based native applications. It provides more security and better calls handling features.
Some of its advantages are as follows:
Background threading: All requests are done in background thread like native applications.
Handling of HTTP code 401: This error code 401 is returned during an unauthorized access to the server which is not handled properly using JavaScript-based HTTP calls.
SSL Pinning: Pinning is used to improve the security of a service. It is used to create a secure Identity for making communications.
Here we will create a new Ionic application with a blank
template by running the following command:
$ ionic start Ionic5HttpNative blank
Go to project root
$ cd Ionic5HttpNative
Install Native HTTP Plugin
Now install the Cordova plugin and Native wrapper for Ionic applications
$ ionic cordova plugin add cordova-plugin-advanced-http
$ npm install @ionic-native/http
Import in App Module
To use HTTP methods in application, open app.module.ts file to import HTTP class then add in providers array as shown below:
//app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { HTTP } from '@ionic-native/http/ngx'; @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule], providers: [ StatusBar, SplashScreen, HTTP, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ], bootstrap: [AppComponent] }) export class AppModule {}
To use HTTP Native plugin in component, first import HTTP
class then add in the constructor
to use its methods:
//home.page.ts import { Component } from '@angular/core'; import { HTTP } from '@ionic-native/http/ngx'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { constructor( private http: HTTP ) { ... ... }
HTTP class of this native plugin provides some Synchronous and Asynchronous methods:
Asynchronous Functions
This category of functions include sendRequest methods like post
, get
, put
, patch
, delete
, head
, uploadFile
and downloadFile
.
They are used with the first two parameters taking URL
and options
object with the last two as success
and error
callbacks.
Check this common format for making sendRequest HTTP calls:
this.http.sendRequest('https://google.com/',
{
method: 'post',
data: { id: 12, message: 'test' },
headers: { Authorization: 'OAuth2: token' },
timeout: 5000
}
)
.then(response => {
// prints 200
console.log(response.status);
})
.catch(response => {
// prints 403
console.log(response.status);
// prints Permission denied
console.log(response.error);
});
Success Callback
then()
method returns an object with 4 properties:
status is the HTTP response code as numeric value.
data is the response from the server as a string.
url is the final URL obtained after any redirects as a string.
headers is an object with the headers.
{
status: 200,
data: '{"id": 12, "message": "test"}',
url: 'http://example.net/rest'
headers: {
'content-length': '247'
}
}
Failure Callback
catch()
method returns an object with 4 properties:
status is the HTTP response code as a numeric value.
error is the error response from the server as a string.
url is the final URL obtained after any redirects as a string.
headers is an object with the headers.
{
status: 403,
error: 'Permission denied',
url: 'http://example.net/noperm'
headers: {
'content-length': '247'
}
}
We can also use specific request types:
Request types, POST, GET, PUT, PATCH, DELETE and HEAD take up 3 parameter objects:
url: The url to send the request to
parameters: Parameters to send with the request
headers: The headers to set for this request
For example here is a POST
method for consuming JSON data response from API endpoint:
this.http.post(
'https://google.com/', //URL
{id: 12, message: 'test'}, //Data
{ Authorization: 'OAuth2: token' } // Headers
)
.then(response => {
// prints 200
console.log(response.status);
try {
response.data = JSON.parse(response.data);
// prints test
console.log(response.data.message);
} catch(e) {
console.error('JSON parsing error');
}
})
.catch(response => {
// prints 403
console.log(response.status);
// prints Permission denied
console.log(response.error);
});
uploadFile
For saving files on the server, we use the uploadFile
method which takes 4 parameters:
url: The url to send the request to
body: The body of the request
headers: The headers to set for this request
filePath: The local path of the file to upload
name: The name of the parameter to pass the file along as
this.http.uploadFile(
'https://google.com/',
{ id: '12', message: 'test' },
{ Authorization: 'OAuth2: token' },
'file:///somepicture.jpg',
'myPictureName'
)
.then(response => {
// prints 200
console.log(response.status);
})
.catch(response => {
// prints 403
console.log(response.status);
// prints Permission denied
console.log(response.error);
});
downloadFile
For downloading a file from the server, there is downloadFile
method which takes 4 parameters:
url: The url to send the request to
body: The body of the request
headers: The headers to set for this request
filePath: The path to download the file to, including the file name.
this.http.downloadFile(
'https://google.com/',
{ id: '12', message: 'test' },
{ Authorization: 'OAuth2: token' },
'file:///somepicture.jpg'
)
.then(response => {
// prints 200
console.log(response.status);
})
.catch(response => {
// prints 403
console.log(response.status);
// prints Permission denied
console.log(response.error);
});
Ionic's Native HTTP plugin also provides Synchronous Functions for getting Authentication headers, setting or getting Cookies and setting Headers. You can check them here for more details.
Thank you this article. Clear and understandable. Maybe, use this native plugin in my project however I have some concern when testing process. If use native http plugin, I cannot test without real device.
Although use native http plugin, testing on browser sound good. However is it possible ?
Hello, this is Teja and thanks for the tutorials. I am getting “okhttp3” error after installing “npm install @ionic-native/http” .