HarmonyOS application development-network requests and web components

Foreword

In today’s world, mobile applications have become an integral part of people’s daily lives. Be it social media, news, shopping or entertainment, the widespread use of Android apps has changed the way we interact with the digital world. However, the actual functionality of these apps goes far beyond interface and user experience. The sophisticated technology and network requests behind them are key to the successful operation of the application, while also providing users with endless possibilities.

In this blog post, we’ll take a deep dive into two important aspects of a HarmonyOS application: network requests and web components. Network requests are the medium through which applications communicate with remote servers, enabling applications to obtain and exchange data to enable various functions such as real-time updates, user authentication, and data storage. At the same time, Web components are a powerful tool that allow applications to embed Web content into applications, providing a rich multimedia and interactive experience.

By learning more about these two topics, we will be able to better understand how to build powerful HarmonyOS applications that meet the needs and expectations of our users. We’ll explore network request techniques and how to handle response data. In addition, we will also look at how to embed web components, such as WebView, to achieve a richer application experience.

HTTP data request

What is HTTP

HTTP is one of the basic protocols in the Internet, responsible for transferring information between clients and servers. How HTTP works is indeed a simple request-response model. When a client (usually a browser) wants to get a web page, image, video, or other resource, it sends an HTTP request to the server. After the server receives the request, it processes the request and returns the corresponding data, and then the client parses and renders the data to present to the user.

This simplicity and scalability of HTTP makes it the basis for data transmission on the Web. Not limited to text and hypertext (HTML), HTTP is also used to transmit images, audio, video and other multimedia content, as well as to implement more advanced applications such as RESTful APIs.

In addition to the above basic working principles, HTTP also involves many elements such as status codes, request methods (such as GET, POST, PUT, DELETE, etc.), request headers and response headers. These elements together constitute the detailed specifications of HTTP requests and responses to ensure Communication reliability and security.

Initiate HTTP request

In HarmonyOS applications, making HTTP requests is a common task for communicating with remote servers. This is achieved through the http module, which provides a rich set of features that allow you to make network requests with ease. Below we’ll cover some key steps to help you understand how to make HTTP requests in HarmonyOS.

First, you need to import the http module to be able to use its functionality. Next, create an httpRequest object that will represent your HTTP request task. Each request requires a separate httpRequest object, so be sure to create a new object for each request.

In some cases, it may be necessary to subscribe to HTTP response header information. This can be achieved by registering a listener. This way you can perform specific actions when response headers are received to suit your business needs.

Then, use the request method to initiate an HTTP request. This method requires two parameters: the requested URL address and an optional HttpRequestOptions object, which contains information about the request method, connection timeout, request header fields, etc. Depending on your needs, you can choose to use GET or POST requests.

Finally, when processing the response results, you need to check the status code of the HTTP response. If the status code is 200 (OK), the request is successful. Next, you can parse the business data returned by the server and use it for further processing by your application.

These simple steps will help you easily initiate HTTP requests in your HarmonyOS application to get the required data or perform other operations. Network communication is one of the cores of modern applications. Through these steps, you can effectively communicate with remote servers and bring more functionality and value to your applications.

import http from '@ohos.net.http';
import Prompt from '@system.prompt';
@Entry
@Component
struct Index {<!-- -->

  build() {<!-- -->
    Row() {<!-- -->
      Column() {<!-- -->
        Button('Initiate network request')
          .width('80%')
          .onClick(() => {<!-- -->
            let httpRequest = http.createHttp();
            let url= "https://EXAMPLE_URL?param1=v1 & amp;param2=v2";
            let promise = httpRequest.request(
              //Request url address
              url,
              {<!-- -->
                // Request method
                method: http.RequestMethod.GET,
                // Optional, default is 60s
                connectTimeout: 60000,
                // Optional, default is 60s
                readTimeout: 60000,
                // Developers add header fields according to their own business needs
                header: {<!-- -->
                  'Content-Type': 'application/json'
                }
              });
            promise.then((data) => {<!-- -->
              if (data.responseCode === http.ResponseCode.OK) {<!-- -->
                console.info('Result:' + data.result);
                console.info('code:' + data.responseCode);
              }
            }).catch((err) => {<!-- -->
              console.info('error:' + JSON.stringify(err));
              Prompt.showToast({<!-- -->
                duration: 3000,
                message: JSON.stringify(err)
              })
            });
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

Web components

Web components are modular, reusable elements used to build web applications. They allow developers to combine specific functionality and user interface elements into larger applications. These components work in an independent manner and can include HTML, CSS, and JavaScript, as well as other resources.

ArkUI provides us with Web components to load web pages. With it, we are equivalent to embedding a browser in our own application, thus displaying various web pages very easily.

Loading web page

Loading online web pages

The use of Web components is very simple. You only need to create a Web component in the ArkTS file in the Page directory and pass in two parameters. Among them, src specifies the referenced web page path, and controller is the controller of the component. The Web component is bound through the controller to control the Web component.

// xxx.ets
@Entry
@Component
struct WebComponent {<!-- -->
  controller: WebController = new WebController();
  build() {<!-- -->
    Column() {<!-- -->
      Web({<!-- --> src: 'https://developer.harmonyos.com/', controller: this.controller })
    }
  }
}

When accessing online web pages, you need to declare network access permissions in the module.json5 file: ohos.permission.INTERNET.

{<!-- -->
    "module" : {<!-- -->
        "requestPermissions":[
           {<!-- -->
             "name": "ohos.permission.INTERNET"
           }
        ]
    }
}

Load local web page

Web components can also load local web pages. First create an HTML file in the main/resources/rawfile directory, and then reference local web resources through $rawfile.

// xxx.ets
@Entry
@Component
struct SecondPage {<!-- -->
  controller: WebController = new WebController();

  build() {<!-- -->
    Column() {<!-- -->
      Web({<!-- --> src: $rawfile('index.html'), controller: this.controller })
    }
  }
}

Properties

Action Description
Enable web page scaling Use the zoomAccess attribute to set whether gestures are supported for zooming.
Perform web page zoom Use the zoom(factor: number) method to set the zoom ratio of the website.
Enable text zoom Use the textZoomAtio(textZoomAtio: number) method to set the text zoom percentage.

Event

Web components also provide methods for handling Javascript dialog boxes, web page loading progress, and various notification and request events. For example, onProgressChange can monitor the loading progress of the web page, onPageEnd triggers the callback when the web page is loaded, and is only triggered in the main frame, and onConfirm triggers the callback when the web page triggers the confirm alarm pop-up window.

// xxx.ets
@Entry
@Component
struct WebComponent {<!-- -->
  controller:WebController = new WebController();
  build() {<!-- -->
    Column() {<!-- -->
      Web({<!-- --> src:$rawfile('index.html'), controller:this.controller })
        .onConfirm((event) => {<!-- -->
          AlertDialog.show({<!-- -->
            title: 'title',
            message: event.message,
            confirm: {<!-- -->
              value: 'onAlert',
              action: () => {<!-- -->
                event.result.handleConfirm();
              }
            },
            cancel: () => {<!-- -->
              event.result.handleCancel();
            }
          })
          return true;
        })
    }
  }
}
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">

Handling page navigation

// xxx.ets
@Entry
@Component
struct Page5 {<!-- -->
  controller: WebController = new WebController();

  build() {<!-- -->
    Column() {<!-- -->
      Row() {<!-- -->
        Button("Forward").onClick(() => {<!-- -->
          this.controller.forward();
        })
        Button("Back").onClick(() => {<!-- -->
          this.controller.backward();
        })
        Button("Refresh").onClick(() => {<!-- -->
          this.controller.refresh();
        })
        Button("Stop").onClick(() => {<!-- -->
          this.controller.stop();
        })
        Button("Clear History").onClick(() => {<!-- -->
          this.controller.clearHistory();
        })
      }
      .padding(12)
      .backgroundColor(Color.Gray)
      .width('100%')

      Web({<!-- --> src: 'https://developer.harmonyos.com/', controller: this.controller })
    }
    .height('100%')
  }
}
</code><img class="look-more-preCode contentImg-no-view" src="//i2.wp.com/csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreBlack.png" alt ="" title="">