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


    概述

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

    样例展示

    基础信息

    image.png

    Http

    介绍

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

    效果预览

    首页结果页

    使用说明

    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()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221

    发起请求:在[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 = ['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%')
    
      }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293
    • 294
    • 295
    • 296
    • 297
    • 298
    • 299
    • 300
    • 301
    • 302
    • 303
    • 304
    • 305
    • 306
    • 307
    • 308
    • 309
    • 310
    • 311
    • 312
    • 313
    • 314
    • 315
    • 316
    • 317
    • 318
    • 319
    • 320
    • 321
    • 322
    • 323
    • 324
    • 325
    • 326
    • 327
    • 328
    • 329
    • 330
    • 331
    • 332
    • 333
    • 334
    • 335
    • 336
    • 337
    • 338
    • 339
    • 340
    • 341
    • 342
    • 343
    • 344
    • 345
    • 346
    • 347
    • 348
    • 349
    • 350
    • 351
    • 352
    • 353
    • 354
    • 355
    • 356
    • 357
    • 358
    • 359
    • 360
    • 361
    • 362
    • 363
    • 364
    • 365
    • 366
    • 367
    • 368
    • 369
    • 370
    • 371
    • 372
    • 373
    • 374
    • 375
    • 376
    • 377
    • 378
    • 379
    • 380
    • 381
    • 382
    • 383
    • 384
    • 385
    • 386
    • 387
    • 388
    • 389
    • 390
    • 391
    • 392
    • 393
    • 394
    • 395
    • 396
    • 397
    • 398
    • 399
    • 400
    • 401
    • 402
    • 403
    • 404
    • 405
    • 406
    • 407
    • 408
    • 409
    • 410
    • 411
    • 412
    • 413
    • 414
    • 415
    • 416
    • 417
    • 418
    • 419
    • 420
    • 421
    • 422
    • 423
    • 424
    • 425
    • 426
    • 427
    • 428
    • 429
    • 430
    • 431
    • 432
    • 433
    • 434
    • 435
    • 436
    • 437
    • 438
    • 439
    • 440
    • 441
    • 442
    • 443
    • 444
    • 445
    • 446
    • 447
    • 448
    • 449
    • 450
    • 451
    • 452
    • 453
    • 454
    • 455
    • 456
    • 457
    • 458
    • 459
    • 460
    • 461
    • 462
    • 463
    • 464
    • 465
    • 466
    • 467
    • 468
    • 469
    • 470
    • 471
    • 472
    • 473

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

    765e5079845b5bb77f2aa30a2da70670.jpeg

  • 相关阅读:
    分布式版本控制git学习笔记
    TikTok营销攻略:如何精准测试与优化品牌营销策略
    maven入门
    无涯教程-JavaScript - SUMIFS函数
    STM32L4R9ZIY6PTR STM32L4高性能嵌入式—MCU
    微服务之流控、容错组件sentinel
    初学phar反序列化
    python基于GDAL的多线程高速批量重采样、对齐栅格、对齐行列数,并无损压缩
    案例|航海知识竞赛需求沟通整理
    现货黄金中如何应用背离?
  • 原文地址:https://blog.csdn.net/m0_62167422/article/details/136510173