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

}
相关推荐
Georgewu38 分钟前
【HarmonyOS Next】鸿蒙加固方案调研和分析
前端·面试·harmonyos
月未央40 分钟前
HarmonyOS Next 开发系列:Provider和Consumer状态修饰器实践
ios·harmonyos
全栈若城1 小时前
16 HarmonyOS NEXT UVList组件开发指南(三)
harmonyos
全栈若城1 小时前
17 HarmonyOS NEXT UVList组件开发指南(四)
harmonyos
HarmonyOS_SDK1 小时前
HarmonyOS SDK让小红书鸿蒙用户尽享原生相机的拍摄之美
harmonyos
沧海一笑-dj2 小时前
【鸿蒙开发】OpenHarmony调测工具hdc使用教程(应用开发者)
华为·harmonyos·鸿蒙·openharmony·hdc·调测工具
花先锋队长11 小时前
鸿蒙生态日日新,鸿蒙原生版支付宝下载量突破230万
华为·harmonyos
星之卡比*12 小时前
前端知识点---库和包的概念
前端·harmonyos·鸿蒙
别说我什么都不会13 小时前
使用Multipass编译OpenHarmony工程
操作系统·嵌入式·harmonyos
轻口味15 小时前
【每日学点HarmonyOS Next知识】多继承、swiper容器、事件传递、滚动安全区域、提前加载网络图片
华为·harmonyos·harmonyosnext