HarmonyOS网络请求的简单用法,HttpUtil简单封装
创始人
2024-12-17 15:37:13
0

请求网络获取数据

在这里插入图片描述

  • 点击按钮发送一个post请求,发送一条string
  • 由于此处的返回result.data本身就是一个string,因此不需要转换类型
      Button('请求网络')         .margin({ top: 10 })         .fontSize(24)         .fontWeight(FontWeight.Bold)         .onClick(() => {            httpRequestPost('http://test.xxx', "你好")             .then((result: ResponseResult) => {               console.log("msg=" + result.msg)               console.log("data=" + result.data)               this.message = result.data.toString()             })          }) 
  • 如果需要类型转换,可以使用as转换
  • result.data as ResponseToken
          httpRequestGet('http://test.xxx')             .then((result: ResponseResult) => {               let data = result.data as ResponseToken               console.log("msg=" + result.msg)               console.log("token=" + data.access_token)             }) 
export class ResponseToken {   access_token: string = "";   expires_in: string = "";   expires_date: string = ""; } 

封装一个HttpUtil

  • 对外开放一个httpRequestGet和httpRequestPost,用于get和post请求
 import { http } from '@kit.NetworkKit'; import ResponseResult from './ResponseResult';  /**  * Initiate an HTTP GET request to the specified URL.  */ export function httpRequestGet(url: string) {   return httpRequest(url, http.RequestMethod.GET); }  /**  * Initiate an HTTP POST request to the specified URL.  */ export function httpRequestPost(url: string, newsData: string) {   return httpRequest(url, http.RequestMethod.POST, newsData); }  /**  * Initiates an HTTP request to a given URL.  *  * @param url URL for initiating an HTTP request  * @param method Request method.  * @param extraData Additional data of the request.  * @returns Returns {@link ResponseResult}.  */ function httpRequest(url: string, method: http.RequestMethod, params?: string): Promise {   let httpRequest = http.createHttp();   let responseResult = httpRequest.request(url, {     method: method,     header: {       'Content-Type': 'application/json'     },     extraData: params   });   let serverData = new ResponseResult();   // Processes the data and returns.   return responseResult.then((value: http.HttpResponse) => {     if (value.responseCode === 200) {       // Obtains the returned data.       let result = `${value.result}`;       let resultJson: ResponseResult = JSON.parse(result);       if (resultJson.code === '000000') {         serverData.data = resultJson.data;       }       serverData.code = resultJson.code;       serverData.msg = resultJson.msg;     } else {       serverData.msg = `Network request failed, please try later!&${value.responseCode}`;     }     return serverData;   }).catch(() => {     serverData.msg = 'Network request failed, please try later!';     return serverData;   }); } 
  • ResponseResult为服务端返回的基本结构
 export default class ResponseResult {   /**    * Code returned by the network request: success, fail.    */   code: string;    /**    * Message returned by the network request.    */   msg: string | Resource;    /**    * Data returned by the network request.    */   data: string | Object | ArrayBuffer;    constructor() {     this.code = '';     this.msg = '';     this.data = '';   }  } 

相关内容

热门资讯

辅助了解!人人燕赵辅助(辅助)... 您好,人人燕赵辅助这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
辅助了解!情怀莆仙吹牛脚本(辅... 辅助了解!情怀莆仙吹牛脚本(辅助)捉住捣蛋鸡都是存在有辅助挂(哔哩哔哩)1、超多福利:超高返利,海量...
详细了解!新518互游插件(辅... 详细了解!新518互游插件(辅助)白金岛歪胡子竟然是真的辅助下载(哔哩哔哩)运新518互游插件辅助工...
教你了解!宝宝吃吃吃外g挂(辅... 教你了解!宝宝吃吃吃外g挂(辅助)开心娱乐一直真的是有辅助软件(哔哩哔哩)1、许多玩家不知道宝宝吃吃...
分享了解!微信开心泉州辅助(辅... 分享了解!微信开心泉州辅助(辅助)怀远麻将本来是真的辅助器(哔哩哔哩)1、实时微信开心泉州辅助透视辅...
关于了解!冰球突破辅助软件(辅... 关于了解!冰球突破辅助软件(辅助)和和嫩江麻将果然是有辅助神器(哔哩哔哩)1.冰球突破辅助软件 选牌...
科普了解!川娱竞技血战辅助器(... 科普了解!川娱竞技血战辅助器(辅助)中至鹰潭麻将原来是真的辅助平台(哔哩哔哩)1、玩家可以在川娱竞技...
推荐了解!微乐小程序辅助(辅助... 推荐了解!微乐小程序辅助(辅助)聚游广东麻将本来有挂辅助软件(哔哩哔哩)1、不需要AI权限,帮助你快...
必备了解!皮皮游戏辅助器(辅助... 必备了解!皮皮游戏辅助器(辅助)盛世2果然有挂辅助安装(哔哩哔哩);1、玩家可以在皮皮游戏辅助器线上...
透视了解!三哥玩透视辅助(辅助... 透视了解!三哥玩透视辅助(辅助)米乐互娱竟然是真的辅助脚本(哔哩哔哩)进入游戏-大厅左侧-新手福利-...