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
  };
}

你可能感兴趣的:(http,笔记,网络协议,鸿蒙)