HarmonyOS鸿蒙Next中如何使用http模块发起网络请求获取数据?

HarmonyOS鸿蒙Next中如何使用http模块发起网络请求获取数据? 我需要从服务器获取数据,http 模块如何使用?如何处理 GET 和 POST 请求?如何解析 JSON 响应?

3 回复

实现思路:

  1. 使用 http.createHttp 创建请求对象,调用 request 方法发起请求:
import { http } from '@kit.NetworkKit';

const httpRequest = http.createHttp();
const response = await httpRequest.request('https://api.example.com/data', {
  method: http.RequestMethod.GET
});
  1. 设置请求头和超时时间:
const response = await httpRequest.request(url, {
  method: http.RequestMethod.GET,
  header: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  },
  connectTimeout: 10000,
  readTimeout: 10000
});
  1. 发送 POST 请求并传递数据:
const response = await httpRequest.request(url, {
  method: http.RequestMethod.POST,
  header: { 'Content-Type': 'application/json' },
  extraData: JSON.stringify({ username: 'test', password: '123456' })
});
  1. 完整示例代码:
import { http } from '@kit.NetworkKit';

interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

interface UserInfo {
  id: string;
  name: string;
  avatar: string;
}

class HttpUtil {
  private baseUrl: string = 'https://api.example.com';

  async get<T>(path: string, params?: Record<string, string>): Promise<T | null> {
    const httpRequest = http.createHttp();
    try {
      let url = `${this.baseUrl}${path}`;
      if (params) {
        const query = Object.entries(params)
          .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
          .join('&');
        url += `?${query}`;
      }

      const response = await httpRequest.request(url, {
        method: http.RequestMethod.GET,
        header: { 'Content-Type': 'application/json' },
        connectTimeout: 10000,
        readTimeout: 10000
      });

      if (response.responseCode === 200) {
        const result = JSON.parse(response.result as string) as ApiResponse<T>;
        if (result.code === 0) {
          return result.data;
        }
      }
      return null;
    } catch (err) {
      console.error(`GET request failed: ${JSON.stringify(err)}`);
      return null;
    } finally {
      httpRequest.destroy();
    }
  }

  async post<T>(path: string, data: Object): Promise<T | null> {
    const httpRequest = http.createHttp();
    try {
      const response = await httpRequest.request(`${this.baseUrl}${path}`, {
        method: http.RequestMethod.POST,
        header: { 'Content-Type': 'application/json' },
        extraData: JSON.stringify(data),
        connectTimeout: 10000,
        readTimeout: 10000
      });

      if (response.responseCode === 200) {
        const result = JSON.parse(response.result as string) as ApiResponse<T>;
        if (result.code === 0) {
          return result.data;
        }
      }
      return null;
    } catch (err) {
      console.error(`POST request failed: ${JSON.stringify(err)}`);
      return null;
    } finally {
      httpRequest.destroy();
    }
  }
}

export const httpUtil = new HttpUtil();

// 使用示例
@Entry
@Component
struct NetworkExample {
  @State userInfo: UserInfo | null = null;
  @State isLoading: boolean = false;

  async aboutToAppear() {
    await this.loadUserInfo();
  }

  async loadUserInfo() {
    this.isLoading = true;
    this.userInfo = await httpUtil.get<UserInfo>('/user/info');
    this.isLoading = false;
  }

  build() {
    Column({ space: 16 }) {
      if (this.isLoading) {
        LoadingProgress().width(40).height(40)
      } else if (this.userInfo) {
        Text(`用户名: ${this.userInfo.name}`).fontSize(18)
        Text(`ID: ${this.userInfo.id}`).fontSize(14)
      } else {
        Text('加载失败').fontSize(16)
      }

      Button('刷新').onClick(() => this.loadUserInfo())
    }
    .width('100%')
    .padding(16)
  }
}

更多关于HarmonyOS鸿蒙Next中如何使用http模块发起网络请求获取数据?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,使用http模块发起网络请求需导入@ohos.net.http模块。创建http.HttpRequest实例,通过request()方法发起请求,配置url、method等参数。在回调中处理响应数据。注意需在module.json5中声明ohos.permission.INTERNET网络权限。

在HarmonyOS Next中,使用@ohos.net.http模块发起网络请求是标准做法。以下是核心步骤:

1. 导入模块与创建实例

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

// 创建http请求实例
let httpRequest = http.createHttp();

2. 发起GET请求

async function httpGet() {
  let url = 'https://example.com/api/data';
  try {
    let response = await httpRequest.request(
      url,
      {
        method: http.RequestMethod.GET,
        header: { 'Content-Type': 'application/json' }
      }
    );
    
    // 获取字符串响应结果
    let result = response.result.toString();
    console.info('Result:' + result);
    
    // 解析JSON数据
    let data = JSON.parse(result);
    handleData(data);
    
  } catch (error) {
    console.error('Request failed:' + JSON.stringify(error));
  }
}

3. 发起POST请求

async function httpPost() {
  let url = 'https://example.com/api/submit';
  let postData = {
    key1: 'value1',
    key2: 'value2'
  };
  
  try {
    let response = await httpRequest.request(
      url,
      {
        method: http.RequestMethod.POST,
        header: { 'Content-Type': 'application/json' },
        extraData: JSON.stringify(postData) // POST请求体数据
      }
    );
    
    let result = response.result.toString();
    let data = JSON.parse(result);
    handleData(data);
    
  } catch (error) {
    console.error('Request failed:' + JSON.stringify(error));
  }
}

4. 关键处理要点

  • 响应解析response.result默认是ArrayBuffer,需通过.toString()转换为字符串后再用JSON.parse()解析
  • 请求方法:使用http.RequestMethod枚举(GET、POST、PUT、DELETE等)
  • 请求头设置:通过header参数配置,JSON接口通常需设置'Content-Type': 'application/json'
  • 错误处理:务必使用try-catch包裹请求代码,处理网络异常和服务器错误
  • 权限配置:在module.json5中声明网络权限:
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

5. 资源释放 请求完成后应及时销毁实例:

httpRequest.destroy();

这种设计遵循了HarmonyOS Next的异步编程模型,使用Promise/async-await处理异步请求,确保UI线程不被阻塞。JSON解析直接使用标准JSON.parse()方法,与Web开发保持一致。

回到顶部