当前位置: 首页 > news >正文

harmony OS NEXT- HTTP 模块笔记

harmony OS NEXT- HTTP 模块笔记

1.基础请求流程

1.1 模块初始化

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

// 创建请求实例(支持连接池复用)
const httpRequest = http.createHttp();

1.2 GET请求基础模板

async function fetchData(url: string): Promise<string> {
  try {
    const response = await httpRequest.request(
      url,
      {
        method: http.RequestMethod.GET,
        header: {
          'Content-Type': 'application/json',
          'User-Agent': 'MyHarmonyApp/1.0.0'
        },
        connectTimeout: 15000,  // 15秒连接超时
        readTimeout: 30000      // 30秒读取超时
      }
    );
    
    if (response.responseCode === http.ResponseCode.OK) {
      return response.result.toString();
    } else {
      throw new Error(`HTTP Error: ${response.responseCode}`);
    }
  } catch (error) {
    console.error(`Network request failed: ${error.code} - ${error.message}`);
    throw error;
  } finally {
    httpRequest.destroy(); // 释放连接资源
  }
}

2.进阶请求配置

2.1 多参数POST请求

const postData = {
  username: 'user123',
  password: 's3cr3tP@ss',
  deviceId: deviceInfo.deviceId // 获取设备信息
};

const response = await httpRequest.request(
  'https://api.example.com/login',
  {
    method: http.RequestMethod.POST,
    header: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + base64.encode('client:secret')
    },
    extraData: httpRequest.stringifyParameters(postData),
    expectDataType: http.HttpDataType.OBJECT // 自动反序列化JSON
  }
);

2.2 文件上传

const filePath = 'data/storage/files/image.jpg';
const file = await fileIo.open(filePath, fileIo.OpenMode.READ_ONLY);

const response = await httpRequest.upload(
  'https://upload.example.com',
  {
    files: [
      {
        filename: 'avatar.jpg',
        name: 'file',
        uri: `internal://app/${filePath}`,
        type: 'image/jpeg'
      }
    ],
    data: [
      {
        name: 'description',
        value: 'Profile photo'
      }
    ]
  }, 
  { 
    method: http.RequestMethod.PUT 
  }
);

3. 网络权限声明

// module.json5
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET",
        "reason": "Required for network access"
      },
      {
        "name": "ohos.permission.GET_NETWORK_INFO",
        "reason": "Check network connectivity"
      }
    ]
  }
}

4.数据解析技巧

4.1 JSON自动解析

{
  // 在请求配置中设置:
  expectDataType: http.HttpDataType.OBJECT
}

// 直接获取结构化数据
const userData = response.result as User;

4.2 XML转换

import convert from 'xml-js';

const xmlText = await response.result.toString();
const jsonData = convert.xml2json(xmlText, {
  compact: true,
  spaces: 2
});

5.实战案例:天气预报应用

interface WeatherData {
  city: string;
  temperature: number;
  humidity: number;
  condition: string;
}

async function getWeather(cityId: string): Promise<WeatherData> {
  const apiUrl = `https://api.weather.com/v3/wx/forecast?city=${cityId}&format=json`;
  const response = await httpRequest.request(apiUrl, {
    headers: {
      'x-api-key': 'your_api_key_here'
    }
  });

  return {
    city: response.result.location.city,
    temperature: response.result.current.temp,
    humidity: response.result.current.humidity,
    condition: response.result.current.phrase
  };
}

相关文章:

  • 【设计模式】享元模式
  • Transformer习题
  • 我开发了一款生成合成数据集的工具
  • 《C++ 函数相关技术解析》
  • 【Paper Tips】随记5-期刊投稿阶段说明
  • 低代码开发平台:企业数字化转型的加速器
  • Linux wifi 驱动移植适配流程详解
  • Java中如何保证高并发的数据安全
  • 高效定位 Go 应用问题:Go 可观测性功能深度解析
  • JavaScript弹出框的使用:对话框、确认框、提示框、弹窗操作
  • 智能体的核心模式和架构
  • [学术][人工智能] 001_什么是神经网络?
  • mapbox基础,使用geojson加载cluster聚合图层
  • leetcode994.腐烂的橘子
  • 使用 2 端口探头测量 40 uOhm(2000 安培)PDN 的挑战 – 需要多少 CMRR?
  • 航空记录器(黑匣子)未来发展趋势
  • Spring MVC 中<mvc:resources> 的两种配置中,`classpath:/static/`和`/static/`有什么不同
  • Python爬虫教程005:ajax的get请求豆瓣电影排行榜
  • html中img标签直接使用border-radius时会图片进行了遮挡
  • 被誉为开源RTOS的天花板ThreadX
  • 专门做照片书的网站/四川seo推广公司
  • 潜江资讯网最新招聘信息/武汉seo优化
  • 深圳疫情防控最新进展/seo优化方案报价
  • 许昌注册公司代办/重庆seo网站收录优化
  • 服务公司名称大全/莆田网站建设优化
  • 域名备案与网站备案的区别/威海网站制作