二十二、网络http请求

发布时间 2024-01-05 10:22:20作者: 创客未来

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

在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网络请求的返回结果。

    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%')
  }
}