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%')
  }
}
相关推荐
岁忧1 天前
GoLang五种字符串拼接方式详解
开发语言·爬虫·golang
tyatyatya1 天前
MATLAB基础数据类型教程:数值型/字符型/逻辑型/结构体/元胞数组全解析
开发语言·matlab
遇到困难睡大觉哈哈1 天前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
心无旁骛~1 天前
python多进程和多线程问题
开发语言·python
星云数灵1 天前
使用Anaconda管理Python环境:安装与验证Pandas、NumPy、Matplotlib
开发语言·python·数据分析·pandas·教程·环境配置·anaconda
kaikaile19951 天前
基于遗传算法的车辆路径问题(VRP)解决方案MATLAB实现
开发语言·人工智能·matlab
寂寞旅行1 天前
解决摄像头/麦克风 在HTTP环境下的调用问题
网络·网络协议·http
遇到困难睡大觉哈哈1 天前
Harmony os——ArkTS 语言笔记(四):类、对象、接口和抽象类
java·笔记·spring·harmonyos·鸿蒙
爱学习的程序媛1 天前
《图解HTTP》核心知识点梳理
网络·网络协议·http·https
四问四不知1 天前
Rust语言进阶(结构体)
开发语言·后端·rust