Web前端之路ArkTS/ArkUI实战零基础学鸿蒙编程

50、鸿蒙/HTTP数据请求

2024-08-14  本文已影响0人  圆梦人生

场景介绍

应用通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。

接口说明

HTTP数据请求功能主要由http模块提供。

使用该功能需要申请ohos.permission.INTERNET权限。

权限申请请参考声明权限

涉及的接口如下表,具体的接口说明请参考API文档

http.png

request接口开发步骤

案例

项目/entry/src/main/module.json5
 "requestPermissions": [
      {
        "name" : "ohos.permission.INTERNET"
      }
],
import { httpRequestPost } from './utils/HttpUtil'
// 定义数据类型接口
interface UserVO {
  createBy: string;
  createTime: string;
  updateBy: string;
  remark: string;
  updateTime: string;
  datetime: string;
  userId: number;
  userName: string;
  // 部门对象
  dept: DeptVO
}
//
interface DeptVO {
  deptName: string;
  deptId: number;
}

@Component
export struct HttpLayout {
  // 存放数据集
  @State list: Array<UserVO> = [];
  build() {
    Column(){
      Button('点击发送请求').onClick(async (event: ClickEvent) => {
        let data = new Map<string, object>();
        data.set("userName", new String("admin"));
        let result = await httpRequestPost('http://ip:端口/user/getList', data)
        //
        this.list = result.data as Array<UserVO>;
        console.log('result ==== ', JSON.stringify(this.list));
      });
      //
      Button('点击修改值').onClick((event: ClickEvent) => {
        // 获取当前下标元素
        if(this.list?.length < 1){return;}
        let currentData = this.list[0]
        // 修改元素的值
        currentData.userName = `${currentData.userName}+update`;
        // 同等位置修改元素,刷新视图(@State监听不到深节点元素值改变)
        this.list.splice(0, 1, currentData);
      });
      // 布局
      Flex({
        direction: FlexDirection.Column
      }){
        ForEach(this.list, (item: UserVO)=>{
          Row(){
            Text(`用户名称:${item.userName};`).lineHeight(22)
            Text(`用户编号:${item.userId};`).lineHeight(22)
            Text(`部门名称:${item.dept.deptName}`).lineHeight(22)
          }
        })
      }
    }
  }
}

HttpUtil.ets

//
import { http } from '@kit.NetworkKit';
//
import { BusinessError } from '@kit.BasicServicesKit';
//
import { ResponseResult } from './ResponseResult';
//
import { JsonUtil } from './JsonUtil'
//
class Constants {
  static readonly HTTP_CODE_200: number = 200;
}
const enum ContentType {
  JSON = 'application/json',
  FORM = 'multipart/form-data'
}
//
export function httpRequestGet(url: string) {
  return httpRequest(url, http.RequestMethod.GET);
}
//
export function httpRequestPost(url: string, params: Map<string, object>) {
  return httpRequest(url, http.RequestMethod.POST, params);
}
//
export function httpRequestGetHtml(url: string) {
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: http.RequestMethod.GET,
    header: {
      'Content-Type': ContentType.JSON
    },
  });

  let serverData = new ResponseResult();
  //
  return responseResult.then((value:http.HttpResponse)=>{
    if(value.responseCode === Constants.HTTP_CODE_200){
      let result = `${value.result}`;
      serverData.data = result;
      serverData.code = 'success'
      serverData.msg = value.header['set-cookie'];
    }else {
      serverData.msg = `${$r('app.string.http_error_message')}&${value.responseCode}`;
    }
    //
    httpRequest.destroy();
    //
    return serverData;
  }).catch((error: Error) => {
    serverData.msg = $r('app.string.http_error_message');
    //
    httpRequest.destroy();
    //
    return serverData;
  });
}
//
function httpRequest(url: string, method: http.RequestMethod, params?: Map<string, object>): Promise<ResponseResult> {
  let httpRequest = http.createHttp();
  let responseResult = httpRequest.request(url, {
    method: method,
    //
    header: {
      'Content-Type': ContentType.JSON,
    },
    //
    extraData: JsonUtil.mapToJsonObj(params)
  });

  let serverData = new ResponseResult();
  //
  return responseResult.then((value:http.HttpResponse)=>{

    if(value.responseCode === Constants.HTTP_CODE_200){

      let result = `${value.result}`;
      let resultJson: ResponseResult = JSON.parse(result);
      serverData.data = resultJson.data;
      serverData.code = resultJson.code;
      serverData.msg = resultJson.msg;
      serverData.has_more = resultJson.has_more;
      serverData.return_count = resultJson.return_count;
      serverData.page_id = resultJson.page_id;
      serverData.code = 'success'
    }else {
      serverData.msg = `${$r('app.string.http_error_message')}&${value.responseCode}`;
    }
    //
    httpRequest.destroy();
    //
    return serverData;
  }).catch((error: Error) => {
    serverData.msg = $r('app.string.http_error_message');
    //
    httpRequest.destroy();
    //
    return serverData;
  });
}

ResponseResult.ets

export class ResponseResult {
  code: string;
  msg: string | Resource;
  data: string | Object | ArrayBuffer;
  has_more: boolean;
  return_count: number;
  page_id: string;

  constructor() {
    this.code = '';
    this.msg = '';
    this.data = '';
    this.has_more = false;
    this.return_count = 0;
    this.page_id = '';
  }
}

JsonUtil.ets

export class JsonUtil {
  /**
   * map转换json字符串
   * @param mapSource
   * @returns
   */
  static mapToJsonStr(mapSource?: Map<string, object>): string{
    let jsonObject: Record<string, Object> = {};
    if(!mapSource){
      return JSON.stringify({});
    }
    //
    mapSource.forEach((value, key) => {
      if (key !== undefined && value !== undefined) {
        jsonObject[key] = value;
      }
    });
    //
    let jsonInfo: string = JSON.stringify(jsonObject);
    //
    return jsonInfo;
  }
  /**
   * map转换json对象
   * @param mapSource
   * @returns
   */
  static mapToJsonObj(mapSource?: Map<string, object>): object{
    //
    let jsonObject = JsonUtil.mapToJsonStr(mapSource);
    //
    return JSON.parse(jsonObject);
  }
}

效果

Http.png
上一篇 下一篇

猜你喜欢

热点阅读