鸿蒙NEXT开发实战:【网络管理-数据请求】

http://www.w3.org/2000/svg" style="display: none;">

概述

本示例仿postman输入API接口地址,获取相应数据,介绍数据请求接口的用法。

样例展示

https://img-blog.csdnimg.cn/img_convert/d9730d8e275625f690920b5bf8aa16fb.png" alt="" />

基础信息

https://img-blog.csdnimg.cn/img_convert/fd429e0eb4c999a980bb2137f0d51f4e.png" alt="image.png" />

Http

介绍

本示例通过[@ohos.net.http]等接口,实现了根据URL地址和相关配置项发起http请求的功能。

效果预览

首页结果页
https://img-blog.csdnimg.cn/img_convert/219ec734b57c3d1d26849f77b4c70c21.png" alt="" />https://img-blog.csdnimg.cn/img_convert/78a1cd28b76fe6435297a340fc4c0f8b.jpeg" alt="" />

使用说明

1.启动应用可配置网络请求,设置网址、请求方式、请求参数;

2.点击确认按钮,跳转请求结果页面;

3.点击返回按钮,返回配置页面;

4.支持将本示例中的http模块编译成tgz包。

具体实现

  • 本示例将发送http请求的接口封装在Http模块,源码参考:[http.ts]
/*

 * Copyright (c) 2022 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import http from '@ohos.net.http'



class Http {

  url: string

  extraData: Object

  options: http.HttpRequestOptions



  constructor() {

    this.url = ''

    this.options = {

      method: http.RequestMethod.GET,

      extraData: this.extraData,

      header: { 'Content-Type': 'application/json' },

      readTimeout: 50000,

      connectTimeout: 50000

    }

  }



  setUrl(url: string) {

    this.url = url

  }



  setMethod(method: string) {

    switch (method) {

      case 'GET':

        this.options.method = http.RequestMethod.GET;

        break

      case 'HEAD':

        this.options.method = http.RequestMethod.HEAD;

        break

      case 'OPTIONS':

        this.options.method = http.RequestMethod.OPTIONS;

        break

      case 'TRACE':

        this.options.method = http.RequestMethod.TRACE;

        break

      case 'DELETE':

        this.options.method = http.RequestMethod.DELETE;

        break

      case 'POST':

        this.options.method = http.RequestMethod.POST;

        break

      case 'PUT':

        this.options.method = http.RequestMethod.PUT;

        break

      case 'CONNECT':

        this.options.method = http.RequestMethod.CONNECT;

        break

      default:

        this.options.method = http.RequestMethod.GET;

        break

    }

  }



  setExtraData(extraData: Object) {

    this.options.extraData = extraData

  }



  setOptions(option: Object) {

    this.options = option

  }



  setList(list: number[], flag: number) {

    list = []

    for (let i = 0; i < flag; i++) {

      list[i] = i

    }

    return list

  }



  setParameter(keys: string[], values: string[]) {

    let result = {}

    for (let i = 0; i <= keys.length - 1; i++) {

      let key = keys[i]

      let value = values[i]

      result[key] = value

    }

    return result

  }



  async request() {

    let httpRequest = http.createHttp()

    httpRequest.on('dataReceive', function (data) {

      AppStorage.SetOrCreate('dataLength', data.byteLength);

      console.info('[ Demo dataReceive ]  ReceivedDataLength: ' + data.byteLength);

    });

    httpRequest.on('dataReceiveProgress', function (data) {

      AppStorage.SetOrCreate('receiveSize', data.receiveSize);

      AppStorage.SetOrCreate('totalSize', data.totalSize);

      console.info('[ Demo dataProgress ]  ReceivedSize: ' + data.receiveSize + ' TotalSize: ' + data.totalSize);

    });

    httpRequest.requestInStream(this.url, this.options);

  }

}



export default new Http()

发起请求:在[MainPage.ets]

/*

 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import router from '@ohos.router'

import Http from '../model/http'



AppStorage.SetOrCreate('receiveSize', 0)

AppStorage.SetOrCreate('totalSize', 0)

AppStorage.SetOrCreate('dataLength', 0)



@Entry

@Component

export struct setting {

  private getUri: string = ''

  private getOption?: object

  @State url: string = ''

  @State option?: object = undefined

  @State flag: number = 1

  @State keys: string[] = []

  @State list: number[] = [0]

  @State values: string[] = []

  @State result: string = ''

  @State method: string = 'GET'

  @State showPage: boolean = false

  @State resultInfo: string = ''

  @State methods: Array<string> = ['GET', 'HEAD', 'OPTIONS', 'TRACE', 'DELETE', 'POST', 'PUT', 'CONNECT']



  @Builder MenuBuilder() {

    Column() {

      ForEach(this.methods, (item: string) => {

        Text(item)

          .margin(5)

          .fontSize(16)

          .textAlign(TextAlign.Center)

          .onClick(() => {

            this.method = item

          })



        Divider().height(1)

      }, (item: string) => item.toString())

    }

    .width('180vp')

  }



  aboutToAppear() {

    this.url = this.getUri

    this.option = this.getOption

    Http.setUrl(this.url)

    let context: Context = getContext(this)

    this.resultInfo = context.resourceManager.getStringSync($r('app.string.result').id)

    setInterval(() => {

      if (Http.url !== '') {

        this.result = "\r\nThe length of the data received by this callback: " +

        JSON.stringify(AppStorage.Get('dataLength') as number) +

        "\r\n" + "The length of the data received: " +

        JSON.stringify(AppStorage.Get('receiveSize') as number) + "\r\n" + "Total length of data: " +

        JSON.stringify(AppStorage.Get('totalSize') as number) + "\r\n" + "Percentage: " +

        JSON.stringify(Math.floor((AppStorage.Get('receiveSize') as number) /

        (AppStorage.Get('totalSize') as number) * 10000) / 100) + '%'

      } else {

        this.result = 'Failed'

      }

    }, 10)

  }



  build() {

    Scroll() {

      Column() {

        if (!this.showPage) {

          Text($r('app.string.configuration'))

            .margin('2%')

            .fontSize(28)



          Row() {

            Text(this.method)

              .width('20%')

              .fontSize(18)

              .textAlign(TextAlign.Center)

              .bindMenu(this.MenuBuilder)

              .margin({ left: 2, right: 4 })



            TextInput({ placeholder: $r('app.string.web') })

              .width('75%')

              .margin({ left: 4, right: 2 })

              .enableKeyboardOnFocus(false)

              .onChange((value: string) => {

                this.url = value

              })

              .id('GET')

          }

          .width('95%')

          .height('10%')



          ForEach(this.list, (item: number, index: number) => {

            Row() {

              Text('Key: ')

                .width('20%')

                .fontSize(18)

                .margin({ left: 2, right: 4 })

                .textAlign(TextAlign.Center)

              TextInput({ placeholder: $r('app.string.key') })

                .width('76%')

                .margin({ left: 4, right: 2 })

                .onChange((value: string) => {

                  this.keys[this.flag - 1] = value

                })

                .id(`key${index + 1}`)

            }

            .width('95%')

            .height('10%')



            Row() {

              Text('Value: ')

                .width('20%')

                .fontSize(18)

                .margin({ left: 2, right: 4 })

                .textAlign(TextAlign.Center)

              TextInput({ placeholder: $r('app.string.value') })

                .width('75%')

                .margin({ left: 4, right: 2 })

                .onChange((value: string) => {

                  this.values[this.flag -1] = value

                })

                .id(`value${index + 1}`)

            }

            .width('95%')

            .height('10%')

          }, (item: number) => item.toString())



          Column() {

            Button($r('app.string.add'))

              .margin(10)

              .fontSize(20)

              .width('60%')

              .onClick(() => {

                this.flag += 1

                this.list = Http.setList(this.list, this.flag)

              })

              .id('add')



            Button($r('app.string.reduce'))

              .margin(10)

              .fontSize(20)

              .width('60%')

              .onClick(() => {

                if (this.flag !== 1) {

                  this.flag -= 1

                }

                this.list = Http.setList(this.list, this.flag)

              })

              .id('reduce')



            Button($r('app.string.reset'))

              .id('reset')

              .margin(10)

              .fontSize(20)

              .width('60%')

              .onClick(() => {

                this.flag = 1

                this.list = [0]

              })



            Button($r('app.string.confirm'))

              .margin(10)

              .fontSize(20)

              .width('60%')

              .onClick(async () => {

                Http.setUrl(this.url)

                Http.setMethod(this.method)

                Http.setExtraData(Http.setParameter(this.keys, this.values))

                try {

                  Http.request()

                } catch (err) {

                  this.result = 'Failed'

                }

                this.showPage = !this.showPage

              })

              .id('submit')



            Button($r('app.string.back'))

              .id('back')

              .margin(10)

              .fontSize(20)

              .width('60%')

              .onClick(() => {

                router.replace({

                  url: 'pages/Index',

                  params: {

                    url: this.url === '' ? Http.url : this.url,

                    option: Http.options

                  }

                })

              })

          }

          .margin({ top: '2%', bottom: '2%' })

          .width('100%')

        } else {

          Text(`${this.resultInfo} ${this.result}`)

            .id(`${this.result === '' || this.result === 'Failed' ? 'failed' : 'succeed'}`)

            .fontSize(20)

            .margin('5%')



          Button($r('app.string.back'))

            .fontSize(25)

            .onClick(() => {

              AppStorage.SetOrCreate('receiveData', 0)

              AppStorage.SetOrCreate('totalSize', 0)

              AppStorage.SetOrCreate('dataLength', 0)

              this.url = ''

              this.flag = 1

              this.keys = []

              this.list = [0]

              this.values = []

              this.result = ''

              this.method = 'GET'

              this.showPage = !this.showPage

            })

            .id('back')

        }

      }

    }

    .width('100%')

    .height('100%')

  }

}

通过TextInput组件获取参数,点击“确认”按钮后通过Http.request()方法调用http.createHttp().request()接口向指定的地址发送请求。
鸿蒙OpenHarmony知识已更新←点

https://img-blog.csdnimg.cn/img_convert/9a9cb03dae41b2a73e3b718be3fdc7a3.jpeg" alt="765e5079845b5bb77f2aa30a2da70670.jpeg" />


http://www.niftyadmin.cn/n/5411087.html

相关文章

【BUG】Maven加上spring-boot-maven-plugin插件还是无法打包.original文件

前言 加入maven插件打包只有一个jar包&#xff0c;没有.original包&#xff0c;运行jar包显示 运行出现 解决方式 1.显示的统一spring-boot-maven-plugin的版本和springboot的版本一致 * (比如我的版本为2.7.2)2.加上如下配置execution的配置 <build><plugins…

Ubuntu 22.04+cmake3.22+opencv3.4

安装C编译器 查看自己的C编译器版本 cmake --version cmake version 3.22.1 如果没有安装cmake&#xff0c;那么可以使用指令自行安装 sudo apt-get install cmake sudo apt-get install build-essential libgtk2.0-dev libavcodec-dev libavformat-dev libjpeg.dev libtif…

原生IP是什么?如何获取海外原生IP?

一、什么是原生IP 原生IP地址是互联网服务提供商&#xff08;ISP&#xff09;直接分配给用户的真实IP地址&#xff0c;无需代理或转发。这类IP的注册国家与IP所在服务器的注册地相符。这种IP地址直接与用户的设备或网络关联&#xff0c;不会被任何中间服务器或代理转发或隐藏。…

修改MonkeyDev默认配置适配Xcode15

上一篇文章介绍了升级Xcode15后&#xff0c;适配MonkeyDev的一些操作&#xff0c;具体操作可以查看&#xff1a;Xcode 15 适配 MonkeyDev。 但是每次新建项目都要去修改那些配置&#xff0c;浪费时间和精力&#xff0c;这篇文章主要介绍如何修改MonkeyDev的默认配置&#xff0…

腾讯云4核8G12M轻量服务器优惠价格446元一年,646元15个月

腾讯云4核8G12M轻量服务器优惠价格446元一年&#xff0c;646元15个月&#xff0c;180GB SSD云硬盘&#xff0c;2000GB月流量。 一张表看懂腾讯云服务器租用优惠价格表&#xff0c;一目了然&#xff0c;腾讯云服务器分为轻量应用服务器和云服务器CVM&#xff0c;CPU内存配置从2核…

Cloud-Sleuth分布式链路追踪(服务跟踪)

简介 在微服务框架中,一个由客户端发起的请求在后端系统中会经过多个不同的服务节点调用来协同产生最后的请求结果,每一个前端请求都会形成一条复杂的分布式服务调用链路,链路中的任何一环出现高延时或错误都会引起整个请求最后的失败 GitHub - spring-cloud/spring-cloud-sl…

flask流式响应

Flask提供了Response对象来处理HTTP响应。可以通过在视图函数中返回一个Response对象&#xff0c;然后使用Response对象的iter方法来实现将数据流式传输到客户端。 1.1 循环生成迭代数据块 from flask import Flask, Response, stream_with_context, requestapp Flask(__nam…

Jacob使用教程--通过宏来寻找变量名

说明&#xff1a; 这里做个随比&#xff0c;参考资料请见前面的系列文章 问题展示&#xff1a; 对于一个操作&#xff0c;当我们不知道怎么利用jacob写代码时,而且网上也找不到&#xff0c;可以按照如下操作&#xff1a; 比如&#xff0c;我们要删除 word中的文本框 我们根本…