Arkts http数据请求

使用Arkts功能需要申请ohos.permission.INTERNET权限。即在module.json5文件中申明网络访问权限:ohos.permission.INTERNET。如下

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

Arkts http数据请求功能主要由http模块提供。具体接口说明如下表。

接口名

功能描述

createHttp()

创建一个http请求。

request()

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

destroy()

中断请求任务。

on(type: 'headersReceive')

扫描二维码关注公众号,回复: 17267749 查看本文章

订阅HTTP Response Header 事件。

off(type: 'headersReceive')

取消订阅HTTP Response Header 事件。

  •  首先需要引入http模块
import http from '@ohos.net.http';
  • 创建一个HTTP请求,返回一个HttpRequest对象
// 每一个httpRequest对应一个http请求任务,不可复用
let httpRequest = http.createHttp();
  • (可选)订阅HTTP响应头。

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

  • (可选)处理HTTP响应头和HTTP网络请求的返回结果。

httpRequest.request('接口地址',{
  method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
  // 开发者根据自身业务需要添加header字段
  header: {
    'Content-Type': 'application/json'
  },
  // 当使用POST请求时此字段用于传递内容
  extraData: {
    "data": "data to send",
  },
  connectTimeout: 60000, // 可选,默认为60s
  readTimeout: 60000, // 可选,默认为60s
}, (err,data) => {
  if (!err) {
    // data.result为http响应内容,可根据业务需要进行解析
    console.info('Result:' + data.result);
    console.info('code:' + data.responseCode);
    // data.header为http响应头,可根据业务需要进行解析
    console.info('header:' + JSON.stringify(data.header));
    console.info('cookies:' + data.cookies); // 8+
  } else {
    console.info('error:' + JSON.stringify(err));
    // 该请求不再使用,调用destroy方法主动销毁。
    httpRequest.destroy();
  }
})

案例:获取诗词接公开API接口

/*
 * 发起http请求
 * */
// 1:导入http模块
import http from '@ohos.net.http'
@Entry
@Component
struct HttpReq {
  @State poem: string = '把酒祝东风'
  @State from:string = '柳宗元'

  aboutToAppear(){
   setInterval(() => {
     // 2. 常见http请求对象
     let httpReq = http.createHttp()
     // 3. 发起请求
     httpReq.request('https://api.apiopen.top/api/sentences',
       {
         method:http.RequestMethod.GET,
       },
       (err,data) => {
         // 4. 处理结果
         if (!err) {
           this.poem = JSON.parse(`${data.result}`).result.name
           this.from = JSON.parse(`${data.result}`).result.from
         }
       }
     )
   },2000)
  }
  build() {
    Row() {
      Column() {
        Text(this.poem)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
        Text(this.from)
          .fontSize(20)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

避免地狱回调

import http from '@ohos.net.http'
@Entry
@Component
struct Index {
  @State info:string = "hello Word !"
  aboutToAppear(){
    let httpReq = http.createHttp()
    // httpReq.request返回的是promise,直接可以链式调用
    let promise = httpReq.request('')
    promise.then((data) =>{
      //可以使用返回值作为参数继续其它请求
      this.info = JSON.parse(`${data.result}`).result.name
    }).catch ((err) =>{
      console.error(err)
    })
  }
  build() {
    Row() {
      Column() {

      }
      .width('100%')
    }
    .height('100%')
  }
}

猜你喜欢

转载自blog.csdn.net/qq_34491508/article/details/134653994
今日推荐