on可以注册监听的字段/事件:off为取消订阅,每一个on都有一个对应的off。

on(type: 'headersReceive'):订阅HTTP Response Header 事件。

off(type: 'headersReceive')

on('dataReceive'):订阅HTTP流式响应数据接收事件。

off('dataReceive')

on('dataEnd'):订阅HTTP流式响应数据接收完毕事件。

off('dataEnd')

on('dataReceiveProgress'):订阅HTTP流式响应数据接收进度事件。

on('dataSendProgress'):订阅HTTP网络请求数据发送进度事件。

点击按钮
 ↓
createHttp() 创建请求实例
 ↓
on(...) 注册监听(先注册)
 ↓
request() 发起请求
 ↓
headersReceive → dataReceive → dataEnd
 ↓
destroy() 释放资源

import http from '@ohos.net.http';

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button('请求 Google:你好')
        .onClick(() => {
          this.requestGoogle();
        })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }

  requestGoogle() {
    let httpRequest = http.createHttp();
    let responseData = '';

    // 1️⃣ 监听响应头
    httpRequest.on('headersReceive', (header) => {
      console.log('状态码:', header.statusCode);
    });

    // 2️⃣ 接收数据(可能多次)
    httpRequest.on('dataReceive', (data) => {
      responseData += data;
    });

    // 3️⃣ 数据接收完成
    httpRequest.on('dataEnd', () => {
      console.log('请求完成,返回内容长度:', responseData.length);
      console.log('返回内容(前500字符):', responseData.slice(0, 500));
      httpRequest.destroy();
    });


    // 5️⃣ 发起 GET 请求
    httpRequest.request(
      'https://www.google.com/search?q=%E4%BD%A0%E5%A5%BD',
      {
        method: http.RequestMethod.GET,
        header: {
          // 模拟浏览器(很关键)
          'User-Agent': 'Mozilla/5.0'
        },
        connectTimeout: 8000,
        readTimeout: 8000
      }
    );
  }
}

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐