Ionic 4|5 Native HTTP Plugin Tutorial with Examples

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…

By.

•

min read

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</pre>
Go to project root
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd Ionic5HttpNative</pre>
<h3>Install Native HTTP Plugin</h3>
Now install the Cordova plugin and Native wrapper for Ionic applications
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ ionic cordova plugin add cordova-plugin-advanced-http
$ npm install @ionic-native/http</pre>
 
<h3>Import in App Module</h3>
To use HTTP methods in application, open<strong> app.module.ts</strong> file to import HTTP class then add in providers array as shown below:
<pre class="lang:js mark:13,23 decode:true">//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 {}
</pre>
 

To use HTTP Native plugin in component, first import <code>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);
      });</pre>
<h4>Success Callback</h4>
<code>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'
  }
}</pre>
 
<h4>Failure Callback</h4>
<code>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'
  }
}</pre>
 

We can also use specific request types:

Request types, <strong>POST</strong>, <strong>GET</strong>, <strong>PUT</strong>, <strong>PATCH</strong>, <strong>DELETE</strong> and <strong>HEAD</strong> take up <strong>3 parameter</strong> objects:

<strong>url</strong>: The url to send the request to
<strong>parameters</strong>: Parameters to send with the request
<strong>headers</strong>: The headers to set for this request

For example here is a <code>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);
     });</pre>
<h3>uploadFile</h3>
For saving files on the server, we use the <code>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);
      });</pre>
<h3>downloadFile</h3>
For downloading a file from the server, there is <code>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.

2 responses to “Ionic 4|5 Native HTTP Plugin Tutorial with Examples”

  1. Ahmet Burak OdabaÅŸ Avatar
    Ahmet Burak OdabaÅŸ

    •

    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 ?

  2. Teja Avatar
    Teja

    •

    Hello, this is Teja and thanks for the tutorials. I am getting “okhttp3” error after installing “npm install @ionic-native/http” .

Leave a Reply

Your email address will not be published. Required fields are marked *