DEV Community

Cover image for Harmonyos fa opening: Using ArkTS to implement HTTP request functionality: Encapsulation of GET and POST requests
liu yang
liu yang

Posted on • Edited on

Harmonyos fa opening: Using ArkTS to implement HTTP request functionality: Encapsulation of GET and POST requests

🌟 Using ArkTS for HTTP requests functionality: Encapsulation of GET and POST requests

When developing HarmonyOS applications, network requests are a common requirement. Whether it is obtaining data or submitting data, interaction with the back-end server is required. In ArkTS, we can use the @ohos.net.http module to implement HTTP requests. The following is an encapsulated HTTP request tool class that supports both GET and POST requests.

Code Analysis

Import the module

import http from '@ohos.net.http';

The http module provided by HarmonyOS has been imported for creating and managing HTTP requests.

  1. Encapsulation of GET requests

export function httpRequestGet(url: string, params? : string) { return httpRequest(url, http.RequestMethod.GET, params); }

An httpRequestGet function is defined for sending GET requests.

Parameter:

url: The requested URL.

params: Optional parameter, used to pass the query string.

Return value: Return a Promise< string> Indicate the result of the request.

  1. Encapsulation of POST requests

export function httpRequestPost(url: string, params? : string) { return httpRequest(url, http.RequestMethod.POST, params); }

An httpRequestPost function is defined for sending POST requests.

Parameter:

url: The requested URL.

params: Optional parameter, used for passing request body data.

Return value: Return a Promise< string> Indicate the result of the request.

  1. General Implementation of HTTP Requests

function httpRequest(url: string, method: http.RequestMethod, params? : string): Promise< string> {

let httpRequest = http.createHttp();

let responseResult = httpRequest.request(

url, {

method: method,

readTimeout: 10000, // read timeout period, optional

header: {

'Content-Type': 'application/json' // Data submission method

},

connectTimeout: 10000, // connection timeout period

extraData: params

}

);

let getjson: string = '';

return responseResult.then((value: http.HttpResponse) => {

console.log(' Request status -- > ' + value.responseCode);

if (value.responseCode === 200) {

console.log(" Request Successful ");

let result = ${value.result};

getjson = result;

} else {

getjson = '';

}

return getjson;

}).catch(() => {

httpRequest.destroy();

return '';

});

}

A general httpRequest function has been defined for handling HTTP requests.

Parameter:

url: The requested URL.

method: Request method, which can be http.RequestMethod.GET or http.RequestMethod.POST.

params: Optional parameter, used to pass query strings or request body data.

Return value: Return a Promise< string> Indicate the result of the request.

Implementation:

Use http.createhttp () to create an HTTP request object.

Send the request using httpRequest.request() to configure the request method, timeout, request header and request body.

In the then callback, check the response status code. If the status code is 200, it indicates that the request was successful and the response result is returned. Otherwise, return an empty string.

In the catch callback, catch the exception and destroy the HTTP request object, returning an empty string.

Usage example

Example of GET request

let url = 'https://api.example.com/data'; httpRequestGet(url).then((data) => {console.log('GET request result: ', data); });

Example of POST request

let url = 'https://api.example.com/submit'; let params = JSON.stringify({ key: 'value' }); httpRequestPost(url, params).then((data) => {console.log('POST request result: ', data); });

Top comments (0)