DEV Community

Cover image for Harmonyos Ark UI network request
liu yang
liu yang

Posted on

Harmonyos Ark UI network request

Adding Internet Permissions and Creating HTTPS Requests

Adding Internet Permissions

To enable internet access, add the following to your module.json5:

"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]
Enter fullscreen mode Exit fullscreen mode

Creating HTTPS Requests

HTTPS is a secure transport protocol that encrypts data between client and server using TLS/SSL. Here's how to create an HTTPS request and log the response.

HTTP Request Utility Class

In OkHttpUtil.ts, create an HTTP request task with createHttp() and send the request with request(). The method supports parameters for URL, options (to set request method, headers, timeouts, etc.), and a callback.

import http from '@ohos.net.http';
import Constants, { ContentType } from '../constant/Constants';
import Logger from './Logger';
import { NewsData } from '../viewmodel/NewsData';

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

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

function httpRequest(url: string, method: http.RequestMethod, params?: NewsData) {
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: method,
    readTimeout: Constants.HTTP_READ_TIMEOUT, // Optional, default is 60000ms
    header: {
      'Content-Type': ContentType.JSON
    },
    connectTimeout: Constants.HTTP_READ_TIMEOUT, // Optional, default is 60000ms
    extraData: params // Request parameters
  });
  return responseResult.then((value: http.HttpResponse) => {
    Logger.error("Request status --> " + value.responseCode);
    if (value.responseCode === 200) {
      Logger.error("Request succeeded");
      let getResult = value.result;
      Logger.error('Response data:', JSON.stringify(getResult));
      return getResult;
    }
  }).catch((err) => {
    return "";
  });
}
Enter fullscreen mode Exit fullscreen mode

Logger Utility Class

import hilog from '@ohos.hilog';

class Logger {
  private domain: number;
  private prefix: string;
  private format: string = '%{public}s, %{public}s';

  constructor(prefix: string = 'MyApp', domain: number = 0xFF00) {
    this.prefix = prefix;
    this.domain = domain;
  }

  debug(...args: string[]): void {
    hilog.debug(this.domain, this.prefix, this.format, args);
  }

  info(...args: string[]): void {
    hilog.info(this.domain, this.prefix, this.format, args);
  }

  warn(...args: string[]): void {
    hilog.warn(this.domain, this.prefix, this.format, args);
  }

  error(...args: string[]): void {
    hilog.error(this.domain, this.prefix, this.format, args);
  }
}

export default new Logger('HTTPS', 0xFF00);
Enter fullscreen mode Exit fullscreen mode

Triggering Requests in the View

Display a button in the view that triggers the HTTPS request when clicked.

import webView from '@ohos.web.webview';
import http from '@ohos.net.http';
import httpGet from '../common/utils/HttpUtil';
import StyleConstant from '../common/constant/StyleConstant';
import CommonConstant from '../common/constant/CommonConstants';
import { httpRequestGet } from '../common/utils/OKhttpUtil';

@Entry
@Component
struct WebPage {
  controller: webView.WebviewController = new webView.WebviewController();
  @State buttonName: Resource = $r('app.string.request_button_name');
  @State webVisibility: Visibility = Visibility.Hidden;
  @State webSrc: string = CommonConstant.DISH;

  build() {
    Column() {
      Row() {
        Image($r('app.media.ic_network_global'))
          .height($r('app.float.image_height'))
          .width($r('app.float.image_width'))
        TextInput({ placeholder: $r('app.string.input_address'), text: this.webSrc })
          .height($r('app.float.text_input_height'))
          .layoutWeight(1)
          .backgroundColor(Color.White)
          .onChange((value: string) => {
            this.webSrc = value;
          })
      }
      .margin({
        top: $r('app.float.default_margin'),
        left: $r('app.float.default_margin'),
        right: $r('app.float.default_margin')
      })
      .height($r('app.float.default_row_height'))
      .backgroundColor(Color.White)
      .borderRadius($r('app.float.border_radius'))
      .padding({
        left: $r('app.float.default_padding'),
        right: $r('app.float.default_padding')
      })
      Row() {
        Web({ src: this.webSrc, controller: this.controller })
          .zoomAccess(true)
          .height(StyleConstant.FULL_HEIGHT)
          .width(StyleConstant.FULL_WIDTH)
      }
      .visibility(this.webVisibility)
      .height(StyleConstant.WEB_HEIGHT)
      .width(StyleConstant.FULL_WIDTH)
      .align(Alignment.Top)
      Row() {
        Button(this.buttonName)
          .fontSize($r('app.float.button_font_size'))
          .width(StyleConstant.BUTTON_WIDTH)
          .height($r('app.float.button_height'))
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.onRequest();
          })
      }
      .height($r('app.float.default_row_height'))
    }
    .width(StyleConstant.FULL_WIDTH)
    .height(StyleConstant.FULL_HEIGHT)
    .backgroundImage($r('app.media.ic_background_image', ImageRepeat.NoRepeat))
    .backgroundImageSize(ImageSize.Cover)
  }

  async onRequest() {
    httpRequestGet(CommonConstant.DISH).then((data) => {
      console.log("Data received: " + data);
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.