HarmonyOS:使用HTTP访问网络

HTTP

一、导入http模块

module.json5里添加网络权限

导入http模块

二、创建http请求

创建http请求

bash 复制代码
import { http } from '@kit.NetworkKit'


function getNetData() {
  // 创建数据请求对象
  let httpRequest = http.createHttp()
}

三、发起请求


请求方法

四、请求示例

GET请求

POST请求

五、处理响应


ResponseCode状态码

六、销毁http

七、 获取鸿蒙专栏网络数据

效果图

testHttp01.ets代码

bash 复制代码
import { http } from '@kit.NetworkKit'
import { BusinessError } from '@kit.BasicServicesKit';
import { JSON } from '@kit.ArkTS';

/**
 * 获取 鸿蒙专栏
 * @returns
 */
function getHarmonySpecialColumn(): string {
  let jsonData = ""
  // 创建数据请求对象
  // 每一个httpRequest对应一个HTTP请求任务,不可复用
  let httpRequest = http.createHttp()

  // 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息
  // 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
  httpRequest.on('headersReceive', (header) => {
    console.info('header: ' + JSON.stringify(header));
  });

  // 开发API https://www.wanandroid.com/blog/show/2
  let baseUrl = "https://www.wanandroid.com/"
  //鸿蒙专栏
  const harmonyJson = "harmony/index/json"

  httpRequest.request(`${baseUrl}${harmonyJson}`, {
    method: http.RequestMethod.GET,
    header: {
      'Content-Type': 'application/json'
    },
    connectTimeout: 60000, // 可选,默认为60000ms
    readTimeout: 60000, // 可选,默认为60000ms
  }, (err: BusinessError, data: http.HttpResponse) => {
    if (err) {
      console.error('error:' + JSON.stringify(err));
      httpRequest.destroy()
    } else {
      jsonData = JSON.stringify(data.result)
      // data.result为HTTP响应内容,可根据业务需要进行解析
      console.info('Result jsonData :' + jsonData);
      console.info('code:' + JSON.stringify(data.responseCode));
      // data.header为HTTP响应头,可根据业务需要进行解析
      console.info('header:' + JSON.stringify(data.header));
      console.info('cookies:' + JSON.stringify(data.cookies)); // 8+
      // 当该请求使用完毕时,调用destroy方法主动销毁
      httpRequest.destroy();
    }
  })

  return jsonData
}

@Entry
@Component
struct TestHttp01 {
  @State message: string = '鸿蒙专栏';

  build() {
    Column() {
      Button("获取鸿蒙专栏")
        .fontColor(Color.Black)
        .fontSize(20)
        .margin({ top: 20 })
        .fontWeight(FontWeight.Medium)
        .onClick((event) => {
          getHarmonySpecialColumn()
        })

    }
    .height('100%')
    .width('100%')
  }
}
相关推荐
人邮异步社区37 分钟前
怎么把C语言学到精通?
c语言·开发语言
爱写代码的阿森40 分钟前
鸿蒙三方库 | harmony-utils之PreferencesUtil用户首选项读写详解
华为·harmonyos·鸿蒙·huawei
心平气和量大福大1 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai1 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
达子6662 小时前
第6章_HarmonyOS 图解 Ability任务调度
华为·harmonyos
এ慕ོ冬℘゜2 小时前
前端基础:什么是时间戳?JS获取时间戳三种方法与实战用途
开发语言·前端·javascript
FrameNotWork2 小时前
HarmonyOS 6.0 分栏布局与折叠适配
华为·harmonyos
执明wa2 小时前
LayoutInflater详解: XML是如何变成View的?
android·xml·开发语言·android studio
一次旅行2 小时前
Python+大模型端到端自动化日报系统
开发语言·python·自动化
爱写代码的阿森2 小时前
鸿蒙三方库 | harmony-utils之PreferencesUtil首选项数据监听详解
服务器·华为·harmonyos·鸿蒙·huawei