How to make Http request in OpenHarmony/HarmonyOS

How to make Http request in OpenHarmony/HarmonyOS

use equipment

Runhe Dayu 200

SDK version: 3.Release applicable

Author: Nuts
Team: Nuts Pie
Public Account: "Big Front-End Journey"
Runkaihong technical expert, Huawei HDE, InfoQ contracted author, OpenHarmony evangelist, good at HarmonyOS application development, familiar with service card development, in the "Battle Code Pioneer" activity As the team leader, Zhong has cultivated three small team leaders and led 100+ team members to complete the submission and integration of Pr.
Welcome to contact me through the homepage or private message, join Nuts, and learn OpenHarmony/HarmonyOS application development together.

The application initiates a data request through HTTP, and supports common GET, POST, OPTIONS, HEAD, PUT, DELETE, TRACE, and CONNECT methods.

The HTTP data request function is mainly provided by the http module.

Effect

image-20230701160611502

Preparation

What we want to achieve this time is the query of oil prices. You can use this API for testing

Here is the corresponding Key value 2b9c1e5d6089c5ddb75dbf32610632bc

interface address:

http://apis.juhe.cn/gnyj/query

Instructions:

Get

Request address:

https://apis.juhe.cn/gnyj/query?key=2b9c1e5d6089c5ddb75dbf32610632bc

Header:
Content-Type:application/x-www-form-urlencoded

permissions

To use this function, you need to apply for ohos.permission.INTERNET permission.

Add permissions in module.json5

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

request interface development steps

1. Import the HTTP module

Import the http namespace from @ohos.net.http.d.ts.

// 引入包名
import http from '@ohos.net.http';

2. Call the createHttp() method,

Create an HttpRequest object.

// 每一个httpRequest对应一个HTTP请求任务,不可复用
let httpRequest = http.createHttp();

3. Call the object's on() method

Subscribe to http response header events, this interface will return before the request request. You can subscribe to this message according to your business needs. (optional)

httpRequest.on('headersReceive', (header) => {
    
    
  console.info('header: ' + JSON.stringify(header));
});

4. Call the request() method of the object

Pass in the url address and optional parameters of the http request to initiate a network request.

httpRequest.request(
  // 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定"EXAMPLE_URL",
  {
    
    
    method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET
    // 开发者根据自身业务需要添加header字段
    header: {
    
    
      'Content-Type': 'application/json'
    },
    // 当使用POST请求时此字段用于传递内容
    extraData: {
    
    
      "data": "data to send",
    },
    expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
    usingCache: true, // 可选,默认为true
    priority: 1, // 可选,默认为1
    connectTimeout: 60000, // 可选,默认为60000ms
    readTimeout: 60000, // 可选,默认为60000ms
    usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定
    usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性
  }, (err, data) => {
    
    
  
  }

5. Analyze the returned results according to actual business needs.

(err, data) => {
    
    
    if (!err) {
    
    
      // data.result为HTTP响应内容,可根据业务需要进行解析
    
    } else {
    
    
      console.info('error:' + JSON.stringify(err));
      
    }

6. Call the object's off() method

Unsubscribe from http response header events.

      httpRequest.off('headersReceive');
  

7. When the request is used up

Call the destroy() method to actively destroy.

      httpRequest.destroy();
    

full code

import http from '@ohos.net.http';
import prompt from '@ohos.prompt';
import promptAction from '@ohos.promptAction';
/**
 * @ProjectName : Oilprice
 * @FileName : WeiXinPage
 * @Author : 坚果
 * @Time : 2023/7/1 14:40
 * @Description : 文件描述
 */

@Component
export struct WeiXinPage {
    
    
  @State data: string = ""

  getHttp() {
    
    


    // 每一个httpRequest对应一个HTTP请求任务,不可复用
    let httpRequest = http.createHttp();

    httpRequest.request(
      "https://apis.juhe.cn/gnyj/query?key=2b9c1e5d6089c5ddb75dbf32610632bc",
      {
    
    
        method: http.RequestMethod.GET, // 可选,默认为http.RequestMethod.GET
        // 开发者根据自身业务需要添加header字段
        header: {
    
    
          'Content-Type': 'application/x-www-form-urlencoded'
        },

        expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型
        usingCache: true, // 可选,默认为true
        priority: 1, // 可选,默认为1
        connectTimeout: 60000, // 可选,默认为60000ms
        readTimeout: 60000, // 可选,默认为60000ms
        usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定

      }, (err, data) => {
    
    
      if (!err) {
    
    
        // data.result为HTTP响应内容,可根据业务需要进行解析
        this.data = JSON.stringify(data.result)
        promptAction.showToast({
    
    

          message: this.data.toString(),
          duration: 6000,
          bottom: 400
        })

        // 当该请求使用完毕时,调用destroy方法主动销毁
        httpRequest.destroy();
      } else {
    
    
        console.info('error:' + JSON.stringify(err));
        // 取消订阅HTTP响应头事件
        httpRequest.off('headersReceive');
        // 当该请求使用完毕时,调用destroy方法主动销毁
        httpRequest.destroy();
      }
    }
    );
    
  }

  build() {
    
    
    Column() {
    
    
      Button("获取数据").onClick(() => {
    
    
        this.getHttp()

      })
      Text(this.data).fontSize(18)
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}

complete

Guess you like

Origin blog.csdn.net/qq_39132095/article/details/131491753