HarmonyOS网络请求的简单用法,HttpUtil简单封装

请求网络获取数据

  • 点击按钮发送一个post请求,发送一条string
  • 由于此处的返回result.data本身就是一个string,因此不需要转换类型
ts 复制代码
      Button('请求网络')
        .margin({ top: 10 })
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .onClick(() => {

          httpRequestPost('http://test.xxx', "你好")
            .then((result: ResponseResult) => {
              console.log("msg=" + result.msg)
              console.log("data=" + result.data)
              this.message = result.data.toString()
            })

        })
  • 如果需要类型转换,可以使用as转换
  • result.data as ResponseToken
ts 复制代码
          httpRequestGet('http://test.xxx')
            .then((result: ResponseResult) => {
              let data = result.data as ResponseToken
              console.log("msg=" + result.msg)
              console.log("token=" + data.access_token)
            })
ts 复制代码
export class ResponseToken {
  access_token: string = "";
  expires_in: string = "";
  expires_date: string = "";
}

封装一个HttpUtil

  • 对外开放一个httpRequestGet和httpRequestPost,用于get和post请求
ts 复制代码
import { http } from '@kit.NetworkKit';
import ResponseResult from './ResponseResult';

/**
 * Initiate an HTTP GET request to the specified URL.
 */
export function httpRequestGet(url: string) {
  return httpRequest(url, http.RequestMethod.GET);
}

/**
 * Initiate an HTTP POST request to the specified URL.
 */
export function httpRequestPost(url: string, newsData: string) {
  return httpRequest(url, http.RequestMethod.POST, newsData);
}

/**
 * Initiates an HTTP request to a given URL.
 *
 * @param url URL for initiating an HTTP request
 * @param method Request method.
 * @param extraData Additional data of the request.
 * @returns Returns {@link ResponseResult}.
 */
function httpRequest(url: string, method: http.RequestMethod, params?: string): Promise<ResponseResult> {
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: method,
    header: {
      'Content-Type': 'application/json'
    },
    extraData: params
  });
  let serverData = new ResponseResult();
  // Processes the data and returns.
  return responseResult.then((value: http.HttpResponse) => {
    if (value.responseCode === 200) {
      // Obtains the returned data.
      let result = `${value.result}`;
      let resultJson: ResponseResult = JSON.parse(result);
      if (resultJson.code === '000000') {
        serverData.data = resultJson.data;
      }
      serverData.code = resultJson.code;
      serverData.msg = resultJson.msg;
    } else {
      serverData.msg = `Network request failed, please try later!&${value.responseCode}`;
    }
    return serverData;
  }).catch(() => {
    serverData.msg = 'Network request failed, please try later!';
    return serverData;
  });
}
  • ResponseResult为服务端返回的基本结构
ts 复制代码
export default class ResponseResult {
  /**
   * Code returned by the network request: success, fail.
   */
  code: string;

  /**
   * Message returned by the network request.
   */
  msg: string | Resource;

  /**
   * Data returned by the network request.
   */
  data: string | Object | ArrayBuffer;

  constructor() {
    this.code = '';
    this.msg = '';
    this.data = '';
  }

}
相关推荐
爱桥代码的程序媛2 小时前
鸿蒙OpenHarmony【轻量系统芯片移植案例】标准系统方案之瑞芯微RK3568移植案例
嵌入式硬件·harmonyos·鸿蒙·鸿蒙系统·移植·openharmony·鸿蒙开发
AORO_BEIDOU2 小时前
防爆手机+鸿蒙系统,遨游通讯筑牢工业安全基石
5g·安全·智能手机·信息与通信·harmonyos
小强在此17 小时前
【基于开源鸿蒙(OpenHarmony)的智慧农业综合应用系统】
华为·开源·团队开发·智慧农业·harmonyos·开源鸿蒙
PlumCarefree20 小时前
基于鸿蒙API10的RTSP播放器(四:沉浸式播放窗口)
华为·harmonyos
中关村科金1 天前
中关村科金推出得助音视频鸿蒙SDK,助力金融业务系统鸿蒙化提速
华为·音视频·harmonyos
小强在此1 天前
基于OpenHarmony(开源鸿蒙)的智慧医疗综合应用系统
华为·开源·团队开发·健康医疗·harmonyos·开源鸿蒙
奔跑的露西ly1 天前
【鸿蒙 HarmonyOS NEXT】popup弹窗
华为·harmonyos
OH五星上将2 天前
OpenHarmony(鸿蒙南向开发)——轻量和小型系统三方库移植指南(一)
嵌入式硬件·移动开发·harmonyos·openharmony·鸿蒙开发·鸿蒙移植
codes234577892 天前
鸿蒙开发之ArkTS 界面篇 一
harmonyos·arkts·harmonyos next·deveco-studio·鸿蒙界面·鸿蒙界面入门·鸿蒙 index.ets