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

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

  • 8
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序三两行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值