0
点赞
收藏
分享

微信扫一扫

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

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

介绍

开发OpenHarmony应用程序时进行数据请求,使用@ohos.net.http模块,每次都需要创建一个http请求任务,然后执行请求方法,最后返回结果。最终造成每个页面都有大量相同的代码,如果域名发生变更,需要每个有数据请求的页面都去更改。因此有了数据请求封装,对外只提供getpost两种方法,只需要导入封装模块,调用封装方法,返回最终结果,把异常等在封装中处理。

知识点

  • @ohos.net.http模块
  • Promise

    实现

    1. 创建RequestUtil.ts文件
    2. 引入@ohos.net.http模块
      import http from '@ohos.net.http';
    3. 引入@ohos.prompt模块,做消息提示
      import prompt from '@ohos.prompt';
    4. 新建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;
    }
    }

    5. 引入[日志工具](https://ost.51cto.com/posts/14627)便于查看返回数据
    ```javascript
    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
    })
    })
    })
    }
  2. 提供getpost方法

    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);
    })
    })
    }
  3. 导出

    let request = new RequestUtil();
    export default request;
  4. 页面引入封装的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

[想了解更多关于开源的内容,请访问:](https://ost.51cto.com/#bkwz)

[51CTO 开源基础软件社区](https://ost.51cto.com#bkwz)

https://ost.51cto.com/#bkwz
举报

相关推荐

0 条评论