HarmonyOS网络数据访问

110 阅读1分钟

一、Http概述 Http:HyperTextTransferProtocol 超文本传输协议 http请求为短连接。客户端发起请求,服务器返回响应,本次连接即结束。 应用请求net权限

image.png 二、Http请求开发步骤

  • 导入http模块
  • 创建http请求
  • 订阅响应事件
  • 发起请求
  • 处理响应
  • 取消订阅--httpRequest.off("headersReceive")
  • 销毁http对象(可选) -- httpRequest.destory()

image.png

image.png

image.png

import { http } from '@kit.NetworkKit' //导入http模块
import { BusinessError } from '@kit.BasicServicesKit'

class Item {
  title?: string
  imgsrc?: string
}

@Entry
@Component
struct NewsPage {
  @State message: string = 'Hello World'
  @State newsList: Item[] = new Array(10)

  aboutToAppear(): void {
    let httpRequest = http.createHttp() //创建http请求
    httpRequest.on('headersReceive', (header) => { //订阅响应事件
      console.info('header: ' + JSON.stringify(header))
    })
    let url = "https://v2.alapi.cn/api/new/toutiao?token=qlVquQZPYSeaCi6u"
    let promise = httpRequest.request( //发起请求
      // 请求url地址
      url,
      {
        // 请求方式
        method: http.RequestMethod.GET,
        // 可选,默认为60s
        connectTimeout: 60000,
        // 可选,默认为60s
        readTimeout: 60000,
        // 可选,默认无此字段
        expectDataType: http.HttpDataType.STRING,
        // 可选,默认为true
        usingCache: true,
        // 可选,默认为1
        priority: 1,
        // 可选,默认值由系统自动指定。
        usingProtocol: http.HttpProtocol.HTTP1_1,
        // 可选,默认为false
        usingProxy: false,
        // 开发者根据自身业务需要添加header字段
        header: {
          'Content-Type': 'application/json'
        }
      })
    promise.then((data) => { //处理响应
      if (data.responseCode === http.ResponseCode.OK) {
        console.info('Result:' + data.result)
        console.info('code:' + data.responseCode)

        this.newsList = JSON.parse(data.result as string)["data"]
      }
    }).catch((err: BusinessError) => {
      console.info('error:' + JSON.stringify(err))
    })
  }

  build() {
    Column() {
      List() {
        ForEach(this.newsList, (item: Item) => {
          ListItem() {
            Row() {
              Text(item.title)
                .margin({ right: 20 })
                .layoutWeight(1)
              Image(item.imgsrc)
                .height(80)
            }
          }
          .padding(20)
          .height(100)
        }, (item: Item) => item.title)
      }
      .divider({strokeWidth: 2})
    }
    .width('100%')
    .height('100%')
  }
}

三、HTTP流式请求开发步骤

  • 订阅更多的响应事件
  • 使用requestInStream发起请求

image.png

  • 取消订阅