Wondering how to Post and Get data with Native HTTP Plugin? We can help you with it.
Here at Bobcares, we have seen several such App-related queries as part of our Development Services for developers.
Today, we will take a look at how to make HTTP calls using Ionic’s Native HTTP plugin.
Know more about Native HTTP calls
Native HTTP calls are made in Android and IOS Native applications. Also, it provides more security and better call handling features.
Moreover, making Native server calls are better and provides more advantages over traditional JavaScript HTTP calls.
Here are some of the advantages of Native HTTP over Javascript requests:
- SSL / TLS Pinning
- CORS restrictions do not apply
- Handling of HTTP code 401
How to Post and Get data with Native HTTP Plugin
Now let’s take a look at how our Engineers make HTTP calls using Ionic’s Native HTTP plugin.
1. Create a basic Ionic Angular app
First, we will create a new ionic application with a blank template by running the following command.
$ ionic start Ionic5HttpNative blank
2. Install Native HTTP Plugin
Next, we install a Cordova plugin and a Native wrapper for ionic applications. For that, we run the below commands.
$ npm install cordova-plugin-advanced-http
$ npm install @ionic-native/http
3. Import in APP Module
To use HTTP methods in application, we import HTTP class to app.modules.ts and 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 {}
In order to use HTTP Native plugin in component, first, we 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
) {
...
...
}
4. GET Requests (Retrieving Data) with Native HTTP Plugin
A GET request will allow us to retrieve data from a particular URL. So we execute a GET request. Takes a URL, parameters, and headers.
getBanners() {
this.http.get(`${this.Url}`, params, header).then(
banners => {
this.banner = JSON.parse(banners.data)
console.log("banner", this. banner )
})
}
We call the GET method and supply it with the URL that we want to make the request.
As well as fetching data from a remote URL, we can also use a GET request to load data from a local file. That would look something similar to the below one:
this.http.get('assets/some-data.json').then((response) => {
console.log(response);
});
This file must be stored along with the applications of other static assets in the assets folder.
5. POST Requests (Sending Data) with Native HTTP Plugin
As well as fetching data from the server, we can also send data to a server through a POST request. A POST request is very similar in nature to a GET request, except that it also contains an additional body/payload parameter:
loadData() {
let operator =
{
deviceId: device_id,
api_token: api_token,
customer_id: customer_id,
service_provider: "",
type: "type",
}
console.log("params:", operator)
let data = this.http.post(`${this.Url}`, operator, {});
data.then(result => {
this.operator = JSON.parse(result.data)
console.log("items", this.operator )
})
}
These functions all take success and error callbacks as their last 2 arguments.
success
The success function receives a response object with 4 properties: status, data, URL, and headers.
Status is the HTTP response code as a 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.
The keys of the returned object are the header names and the values are their respective header values. All header names must be in lowercase.
Here’s a quick example:
{
status: 200,
data: '{"id": 12, "message": "test"}',
url: 'http://example.net/rest'
headers: {
'content-length': '247'
}
}
Most APIs will return JSON which means that we must parse the data like in the example below:
cordova.plugin.http.post('https://google.com/', {
id: 12,
message: 'test'
}, { Authorization: 'OAuth2: token' }, function(response) {
console.log(response.status);
try {
response.data = JSON.parse(response.data);
console.log(response.data.message);
} catch(e) {
console.error('JSON parsing error');
}
}, function(response) {
console.log(response.status);
console.log(response.error);
});
Failure
The error function receives a response object with 4 properties: status, error, URL, and headers (URL and headers being optional).
Status is an HTTP response code or an internal error code. Positive values are HTTP status codes whereas negative values do represent internal error codes.
Error is the error response from the server as a string or an internal error message.
Url is the final URL obtained after any redirects as a string.
Headers is an object with the headers. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
Here’s a quick example:
code{
status: 403,
error: 'Permission denied',
url: 'http://example.net/noperm'
headers: {
'content-length': '247'
}
}
[Need any assistance with the Native HTTP plugin? – Our experts can help you]
Conclusion
Today, we learned how to post and get data with the Native HTTP plugin.
0 Comments