HarmonyOS使用HTTP库实现与后端数据交互

作者:

在

在模块目录的module.json5模块配置文件中加入网络权限,如下图所示:

我这里模块名是entry,所以module.json5文件在entry/src/main/etc目录中,代码原文:

"requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ],

需要在page.ets中引入http,如下:

import { http } from '@kit.NetworkKit';

或者:

import http from ‘@ohos.net.http’;

我的成功示例:


import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit'

@Entry
@Component
struct Index {
  @State message: string = 'Hello World2';

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          console.log('111');
          this.message = 'Welcome';
          let httpRequest = http.createHttp();
          let url = "https://nb.oihw.cn/addons/nianbao/api.index"
          let extraData = JSON.stringify({ id: 1 }); // 将extraData转换为JSON字符串
          httpRequest.request(url, {
            method: http.RequestMethod.POST,
            extraData: extraData,
            header: {
              'Content-Type': 'application/json'
            }
          }, (err: BusinessError, data: http.HttpResponse) => {
            if (!err) {
              console.log(JSON.parse(JSON.stringify(data.result)));
              this.data = JSON.parse(JSON.stringify(data.result))
            } else {
              console.error('error:' + JSON.stringify(err));
            }
          })
        })
      Button('下一页')
        .onClick(() => {
          this.message = 'ArkUI'
        })
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .width('100')
        .height(50)
        .margin({top: 120})
    }
    .height('100%')
    .width('100%')
  }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注