天天看点

#夏日挑战赛#OpenHarmony工具集之数据请求封装·让获取数据变简单

本文正在参加星光计划3.0–夏日挑战赛

介绍

开发OpenHarmony应用程序时进行数据请求,使用

@ohos.net.http

模块,每次都需要创建一个

http

请求任务,然后执行请求方法,最后返回结果。最终造成每个页面都有大量相同的代码,如果域名发生变更,需要每个有数据请求的页面都去更改。因此有了数据请求封装,对外只提供

get

post

两种方法,只需要导入封装模块,调用封装方法,返回最终结果,把异常等在封装中处理。

知识点

  • @ohos.net.http

    模块
  • Promise

实现

  1. 创建

    RequestUtil.ts

    文件
  2. 引入

    @ohos.net.http

    模块
import http from '@ohos.net.http';
           
  1. 引入

    @ohos.prompt

    模块,做消息提示
import prompt from '@ohos.prompt';
           
  1. 新建

    RestApiUtil.ts

    文件,作为返回结果集
/**
 * @Description 返回数据工具
 * @date 2022/7/18 9:41
 * @Author Bai XiaoMing
 * @Version 1.0
 */
export default class RestApiUtil {
    code: number;
    msg: string;
    newslist: Array<any>;

    constructor(code: number, msg: string, newslist: Array<any>) {
        this.code = code;
        this.msg = msg;
        this.newslist = newslist;
    }
}
           
  1. 引入日志工具便于查看返回数据
import log from './LogUtil';
           
  1. 封装私有请求

    request

    方法
private request(url: string, method: http.RequestMethod.GET | http.RequestMethod.POST, data?: any): Promise<any> {
        return new Promise((resolve) => {
            let request = http.createHttp();
            request.request(url, {
                method,
                header: {
                    "Content-Type": method === http.RequestMethod.GET ? "application/json" : "application/x-www-form-urlencoded;charset=UTF-8"
                },
                extraData: data
            }).then((res) => {
                log.printInfo(TAG, JSON.stringify(res));
                let { responseCode, result } = res;
                if (responseCode === 200) {
                    log.printInfo(TAG, result.toString());
                    let data = result.toString();
		    // 将返回结果转成封装的结果集
                    let resultVal: RestApi = JSON.parse(data);
                    resolve(resultVal);
                } else {
                    prompt.showToast({
                        message: "HTTP级异常:" + res.responseCode,
                        duration: 2000
                    })
                }
            }).catch((err) => {
                prompt.showToast({
                    message: "系统级异常:" + JSON.stringify(err),
                    duration: 2000
                })
            })
        })
    }
           
  1. 提供

    get

    post

    方法
get(url: string, data?: any): Promise<any> {
        return new Promise((resolve) => {
            this.request(url, http.RequestMethod.GET, data).then((res) => {
                resolve(res);
            })
        })
    }

    post(url: string, data?: any): Promise<any> {
        return new Promise((resolve) => {
            this.request(url, http.RequestMethod.POST, data).then((res) => {
                resolve(res);
            })
        })
    }
           
  1. 导出
let request = new RequestUtil();
export default request;
           
  1. 页面引入封装的

    RequestUtil

    ,调用

    get

    方法获取请求数据
import request from '../common/utils/RequestUtil';

// 【天行数据】提供的藏头诗接口,返回数据
  getPoetry = () => {
    this.poetryArray = new Array<any>();
    let url = 'https://api.tianapi.com/cangtoushi/index';
    url += `?key=${Constant.RequestApiKey}`;
    url += `&word=${this.word}`;
    url += `&len=${this.len}`;
    url += `&type=${this.type}`;
    url += `&pat=${this.pat}`;
    request.get(url).then((res) => {
	// 返回结果没有进一步处理,读者有兴趣可以进一步封装
      log.printInfo(TAG, JSON.stringify(res));
      let data: RestApi = res;
      if (data.code === 250) {
        prompt.showToast({
          message: data.msg,
          duration: 2000
        })
      } else if (data.code === 200) {
        this.poetryArray = data.newslist;
      } else {
        prompt.showToast({
          message: data.msg,
          duration: 2000
        })
      }
    })
  }
           
至此,数据请求二次封装完成。

附件链接:https://ost.51cto.com/resource/2184

继续阅读