harmonyOS HTTP数据请求能用类

通用类

import http from '@ohos.net.http';

// 调试开关
const Test: boolean = true;

// API 地址
const Url: string = Test ? 'http://api.林.cn/' : 'http://api.林.cn/';

export function request(api: string, method: string, data: any, token: string = ''): Promise<any> {
   
  return new Promise((resolve, reject) => {
   
    // 构建完整的 URL
    const url = Url + api;

    // 创建 http 模块实例
    const httpRequest = http.createHttp();

    // 根据 'method' 参数确定请求方法
    const requestMethod = getRequestMethod(method);

    // 要添加的额外标头
    const customHeaders = {
   
      'Content-Type': 'application/json',
      'Authorization': token // 在这里添加您的自定义标头
    };

    // 发起 HTTP 请求
    const promise = httpRequest.request(
      url,
      {
   
        method: requestMethod,
        extraData: data,
        connectTimeout: 60000, // 60 秒
        readTimeout: 60000,
        header: {
    ...customHeaders } // 扩展自定义标头
      }
    );

    // 处理 Promise 的解析
    promise.then((responseData) => {
   
      if (responseData.responseCode === http.ResponseCode.OK) {
   
        resolve(responseData); // 使用响应数据解析 Promise
      } else {
   
        console.error('错误 - 响应代码: ' + responseData.responseCode);
        reject(new Error('HTTP 请求失败,响应代码为 ' + responseData.responseCode));
      }
    }).catch((error) => {
   
      console.error('错误: ' + JSON.stringify(error));
      reject(error); // 使用错误拒绝 Promise
    });
  });
}

// 辅助函数,将方法字符串映射到 http.RequestMethod
function getRequestMethod(method: string): http.RequestMethod {
   
  switch (method.toLowerCase()) {
   
    case 'get':
      return http.RequestMethod.GET;
    case 'post':
      return http.RequestMethod.POST;
    case 'put':
      return http.RequestMethod.PUT;
    case 'delete':
      return http.RequestMethod.DELETE;
    // 针对其他 HTTP 方法需要添加更多的情况
    default:
      throw new Error(`不支持的 HTTP 方法: ${
     method}`);
  }
}



调用方式


import {
    request } from '../tools/httpUtils';
@Entry //入口
@Component  //装饰
struct Index {
   
  @State message: string = '啾啾救援' //双向绑定
  build() {
   
    Row() {
   
      Column() {
   
        Image("http://www.jjsos.cn/images/menu_logo.png").width(300).interpolation(ImageInterpolation.High)
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button('确定').fontSize(30).backgroundColor("#000").onClick(()=>{
   
          this.message="JJSOS"
        })
        TextInput({
   placeholder:'用户名'}).type(InputType.PhoneNumber)
        TextInput({
   placeholder:'密码'}).type(InputType.Password)
        Button('确定登陆').onClick(()=>{
   
          const requestData = {
   
            "type": "1",
            "username": "13176630659",
            "password": "123456"
          };
          const  authToken:string=""
          const apiEndpoint = 'v2/auth/get-access-token';
          request(apiEndpoint, 'post', requestData, authToken)
            .then((responseData) => {
   
              // 这时写代码 
              console.log('Response:', responseData);
              // Perform actions based on the response
            })
            .catch((error) => {
   
              // Handle errors
              console.error('Error:', error);
              // Perform error-specific actions
            });

        })
      
      }
      .width('100%').backgroundColor("#aaa")
    }
    .height('100%').backgroundColor("#aaa")
  }
}

function authToken(apiEndpoint: string,arg1: string,requestData: {
    type: string; username: string; password: string; },authToken: any) {
   
throw new Error('Function not implemented.');
}

相关推荐

  1. harmonyOS HTTP数据请求

    2023-12-13 06:02:03       46 阅读
  2. jquery如何请求ajax请求数据

    2023-12-13 06:02:03       34 阅读
  3. MFC常数据类型:CRect

    2023-12-13 06:02:03       31 阅读
  4. AJAX-常请求方法和数据提交

    2023-12-13 06:02:03       39 阅读
  5. 关于RestController发送请求List<T> 接收数据

    2023-12-13 06:02:03       42 阅读
  6. 页面中异步请求数据,python爬虫爬到吗

    2023-12-13 06:02:03       38 阅读
  7. pytest封装请求

    2023-12-13 06:02:03       47 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-13 06:02:03       91 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-13 06:02:03       97 阅读
  3. 在Django里面运行非项目文件

    2023-12-13 06:02:03       78 阅读
  4. Python语言-面向对象

    2023-12-13 06:02:03       88 阅读

热门阅读

  1. Node.js中的EventEmitter类介绍

    2023-12-13 06:02:03       67 阅读
  2. Ansible批量安装Zabbix-agnet客户端

    2023-12-13 06:02:03       54 阅读
  3. ARM(中断实验) 2023.12.12

    2023-12-13 06:02:03       56 阅读
  4. 对virsh dumpxml 文件的解释

    2023-12-13 06:02:03       60 阅读
  5. 使用ansible命令部署k8s集群

    2023-12-13 06:02:03       56 阅读
  6. FFmpeg之HWContextType

    2023-12-13 06:02:03       62 阅读
  7. ffmpeg编解码——时间基(time base)概念

    2023-12-13 06:02:03       56 阅读
  8. .NET6 RabbitMQ自动重连

    2023-12-13 06:02:03       54 阅读
  9. 使用elasticsearch-dump工具备份ES数据库

    2023-12-13 06:02:03       63 阅读
  10. Android & iOS - Android Studio/Xcode历史版本下载

    2023-12-13 06:02:03       59 阅读
  11. Flink之状态编程

    2023-12-13 06:02:03       47 阅读