#鸿蒙通关秘籍#如何使用h_request库在HarmonyOS中简化HTTP请求?

HarmonyOS
22h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
hm673ff0fa9b71d

为了在HarmonyOS中实现简化HTTP请求,可以使用轻量级网络请求库h_request。以下是具体步骤:

  1. 安装h_request库:确保项目中安装了h_request库。

    ohpm install @yyz116/h_request
    
  2. 创建网络请求封装:在util/http.ts文件中,定义网络请求封装,使其全局可用。

    import Request, { HttpRequestConfig, HttpResponse } from '@yyz116/h_request';
    import { Log } from './logutil';
    
    const $u = {
      http: new Request(),
    };
    
    globalThis.$http = $u.http;
    
    export const setRequestConfig = () => {
      globalThis.$http.setConfig((config: HttpRequestConfig) => {
        config.baseURL = "http://175.178.126.10:8000/api/v1";
        return config;
      });
    
      globalThis.$http.interceptors.request.use(
        (config) => {
          Log.debug('请求拦截');
          return config;
        },
        (error) => {
          return Promise.reject(error);
        }
      );
    
      globalThis.$http.interceptors.response.use(
        (response: HttpResponse) => {
          Log.debug('响应拦截');
          if (response.data.code === 401) {
            console.log('请登录');
            setTimeout(() => {
              console.log('请登录');
            }, 1000);
          }
          return response;
        },
        (error) => {
          return Promise.reject(error);
        }
      );
    };
    
  3. 定义接口数据格式:在apiTypes.ts文件中,定义接口数据格式。

    type AnyObject = Record<string | number | symbol, any>;
    
    export interface BaseResponse<T> {
      status: number;
      statusText: string;
      header?: AnyObject;
      data: T;
    }
    
    export interface ZhiNewsItem {
      id: string;
      image: string;
      title: string;
      url: string;
      hint: string;
      date: string;
    }
    
    export interface ZhiNewsRespData {
      code: number;
      message: string;
      stories: Array<ZhiNewsItem>;
      top_stories: Array<ZhiNewsItem>;
      date: string;
    }
    
    export interface ZhiDetailRespData {
      code: number;
      message: string;
      content: Array<{ types: string; value: string }>;
      title: string;
      author: string;
      bio: string;
      avatar: string;
      image: string;
      more: string;
    }
    
  4. 实现API接口:在zhihuapi.ts文件中,实现API接口的调用。

    import { setRequestConfig } from '../../utils/http';
    import { BaseResponse, ZhiNewsRespData, ZhiDetailRespData } from '../bean/ApiTypes';
    
    setRequestConfig();
    
    const http = globalThis.$http;
    
    export const getZhiHuNews = (date: string): Promise<BaseResponse<ZhiNewsRespData>> => {
      return http.get('/zhihunews/' + date);
    };
    
    export const getZhiHuDetail = (id: string): Promise<BaseResponse<ZhiDetailRespData>> => {
      return http.get('/zhihudetail/' + id);
    };
    
  5. 使用示例:根据需要在业务逻辑中调用API。

    @Component
    export default struct ZhiHu {
      @State message: string = 'Hello World';
    
      aboutToAppear() {
        Log.info('ZhiHu aboutToAppear');
        this.currentDate = formatDate(new Date());
    
        getZhiHuNews(this.currentDate).then((res) => {
          this.zhiNews = res.data.stories;
        }).catch((err: BaseResponse<ErrorResp>) => {
          Log.debug("请求错误", err.data.message);
        });
      }
    
      aboutToDisappear() {
        Log.info('ZhiHu aboutToDisappear');
      }
    }
    
分享
微博
QQ
微信
回复
21h前
相关问题
http request 请求不到接口数据
4843浏览 • 1回复 待解决