二十二、网络http请求、promise

网络请求需要添加网络访问权限:

在module.json5文件中添加。

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

开发步骤:

1. import 需要的http模块。

import http from '@ohos.net.http'

 

2. 创建一共HTTP请求,防护一个HttpRequest对象。

let httpReq = http.createHttp()

 

3. 订阅HTTP响应头。

4 . 根据URL地址,发起HTTP网络请求。

5. 处理HTTP相应头和HTTP网络请求的返回结果。

https://api.apiopen.top/api/sentences  ---->随机诗词API
    httpReq.request('https://api.apiopen.top/api/sentences',{
      method:http.RequestMethod.GET
    }, (err,data) => {
        //4. 处理结果
        if(!err){
          let name = JSON.parse(`${data.result}`).result.name
          this.poem = name
        }
    })

 案例代码:

// 1.导入http模块
import http from '@ohos.net.http'
@Entry
@Component
struct HttpReq {
  @State poem: string = '把酒问青天'

  //生命周期函数
  aboutToAppear(){
    //2. 创建http请求对象
    let httpReq = http.createHttp()
    //3. 发起请求
    httpReq.request('https://api.apiopen.top/api/sentences',{
      method:http.RequestMethod.GET
    }, (err,data) => {
        //4. 处理结果
        if(!err){
          let name = JSON.parse(`${data.result}`).result.name
          this.poem = name
        }
    })
  }

  build() {
    Row() {
      Column() {
        Text(this.poem)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

 

Promise请求:

import http from '@ohos.net.http';
@Entry
@Component
struct HttpReqPromise {
  @State poem: string = '把酒问青天'
  @State from: string = ''

  //生命周期函数
  aboutToAppear(){
    let httpReq = http.createHttp()
    let promise = httpReq.request('https://api.apiopen.top/api/sentences')
    promise.then((data) => {
      this.poem = JSON.parse(`${data.result}`).result.name
      this.from = JSON.parse(`${data.result}`).result.from
    }).catch((err) => {
      console.log(err)
    })
  }

  build() {
    Row() {
      Column() {
        Text(this.poem)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
        Text(this.from)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

 

posted @ 2024-01-05 10:18  创客未来  阅读(31)  评论(0编辑  收藏  举报