蓝河应用(BlueOS)如何发起数据请求【坚果派-坚果】

124 阅读3分钟

蓝河应用(BlueOS)如何发起数据请求【坚果派-坚果】

上一节我们完成了路由跳转,这一节我们来看一下如何数据请求。

作者:坚果

华为HDE,润开鸿生态技术专家,坚果派创始人,OpenHarmony布道师,开发者联盟优秀讲师,2023年开源之夏导师,2023年OpenHarmony应用创新赛导师,OpenHarmony金融应用创新赛导师,RISC-V+OpenHarmony应用创意赛导师,OpenHarmony三方库贡献者,开放原子开源基金会技术+生态贡献者,第一批开放原子开源讲师,曾受邀参加2022,2023HDC大会,OpenHarmony校源行开源大使,InfoQ签约作者,CSDN博客专家,电子发烧友MVP,51CTO博客专家博主,阿里云博客专家,专注于分享的技术包括HarmonyOS/OpenHarmony,ArkUI-X,元服务,服务卡片,华为自研语言,在2022年战码活动中,带领100余人完成pr的提交,配合孵化三个小队长。也在此活动中累计完成1.5W行代码提交,在2023年OpenHarmony创新赛中。累计辅导60+队伍,完成作品的提交,并有9个获奖。在2023年OpenHarmony金融应用创新赛中。累计辅导14+队伍,完成作品的提交。

一、接口声明

在src/manifest.json中声明权限。

{ "name": "blueos.network.fetch" }

二、导入模块

在script中导入模块。

import fetch from '@blueos.network.fetch'const fetch = require('@blueos.network.fetch')

三、查看接口文档fetch.fetch(OBJECT)

参数:

参数名类型必填说明
urlString资源 url
dataString/Object/ArrayBuffer请求的参数,可以是字符串,或者是 js 对象、arraybuffer 对象。参考 data与Content-Type关系 部分
headerObject请求的 header,会将其所有属性设置到请求的 header 部分。User-Agent 设置在版本开始支持。示例:{"Accept-Encoding": "gzip, deflate","Accept-Language": "zh-CN,en-US;q=0.8,en;q=0.6"}
methodString默认为 GET,可以是:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT
responseTypeString支持返回类型是 text,json,file,arraybuffer,默认会根据服务器返回 header 中的 Content-Type 确定返回类型,详见 success返回值
successFunction成功返回的回调函数
failFunction失败的回调函数,可能会因为权限失败
completeFunction结束的回调函数(调用成功、失败都会执行)

data 与 Content-Type 关系

dataContent-Type说明
String不设置Content-Type 默认为 text/plain,data 值作为请求的 body
String任意 Typedata 值作为请求的 body
Object不设置Content-Type 默认为 application/x-www-form-urlencoded,data 按照 url 规则进行 encode 拼接作为请求的 body
Objectapplication/x-www-form-urlencodeddata 按照 url 规则进行 encode 拼接作为请求的 body
Objectapplication/x-www-form-urlencoded 之外的任意 type会将 data 转为字符串作为请求的 body
ArrayBuffer不设置Content-Type 默认为 application/octet-stream,data 值作为请求的 body
ArrayBuffer任意 Typedata 值作为请求的 body

success 返回值:

参数名类型说明
codeInteger服务器状态 code
dataString/Object /ArrayBuffer参考 responseType与success中data关系 部分
headersObject服务器 response 的所有 header

responseType 与 success 中 data 关系:

responseTypedata说明
String服务器返回的 header 中 type 是 text/*或 application/json、application/javascript、application/xml,值是文本内容,否则是存储的临时文件的 uri,临时文件如果是图片或者视频内容,可以将图片设置到 image 或 video 控件上显示
textString返回普通文本
jsonObject返回 js 对象
fileString返回存储的临时文件的 uri
arraybufferArrayBuffer返回 ArrayBuffer 对象

四、发起请求

完整源码

     onBtnClick()  {
       fetch.fetch({
  url: 'https://v2.alapi.cn/api/mingyan?token=qlVquQZPYSeaCi6u',
    header: {
          'Content-Type': 'application/json'
        },
  success: function (response) {
    console.log(`the status code of the response: ${response.code}`)
   
    console.log(`the headers of the response: ${JSON.stringify(response.data)}`)
  },
  fail: function (data, code) {
    console.log(`handling fail, errMsg = ${data}`)
    console.log(`handling fail, errCode = ${code}`)
  },
})
  }

查看控制台输出。

image-20231230163321005

五、完整源码

完整源码

<template>
  <div class="wrapper">
    <text class="title">{{ title }} </text>
    <text>{{ key }}</text>
    <text>{{ message.data.content }}</text>
    <text>{{ '作者:' + message.data.author }}</text>
    <input
      class="btn"
      type="button"
      value="获取网络数据"
      onclick="onBtnClick"
    />
  </div>
</template>
<script>
import fetch from '@system.fetch'
console.log(typeof fetch.fetch)
export default {
  data: {
    title: '👏欢迎来到首页',
    key: '',
    message: ""
  },
  onBtnClick() {
    fetch.fetch({
      url: 'https://v2.alapi.cn/api/mingyan?token=qlVquQZPYSeaCi6u',
      header: {
        'Content-Type': 'application/json'
      },
      success: (response) => {
        console.log(`the status code of the response: ${response.code}`)
        console.log(`the status code of the response: ${JSON.stringify(response.data)}`)
        //console.log(JSON.parse(response.data))
        this.message = JSON.parse(response.data)
        //console.log(`the headers of the response: ${JSON.stringify(response)}`)
        console.log(typeof fetch.fetch)
​
      },
      fail: (data, code) => {
        console.log(`handling fail, errMsg = ${data}`)
        console.log(`handling fail, errCode = ${code}`)
      },
    })
  },
  onInit() {
​
    // js中输出页面传递的参数
    console.info('key: ' + this.key)
​
  },
​
}
</script><style lang="scss">
@import './../../assets/styles/style.scss';
.wrapper {
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #ffffff;
}
.title {
  text-align: center;
  color: #212121;
}
.btn {
  width: 55 * $size-factor;
  height: 12 * $size-factor;
  border-radius: 7 * $size-factor;
  background-color: $brand;
  color: $white;
  font-size: 5 * $size-factor;
  margin-top: 7 * $size-factor;
}
</style>

效果

效果预览

参考文档

数据请求