欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 幼教 > HarmonyOS网络请求的简单用法,HttpUtil简单封装

HarmonyOS网络请求的简单用法,HttpUtil简单封装

2024/10/24 9:18:39 来源:https://blog.csdn.net/yu540135101/article/details/140637289  浏览:    关键词:HarmonyOS网络请求的简单用法,HttpUtil简单封装

请求网络获取数据

在这里插入图片描述

  • 点击按钮发送一个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 ResponseTokenconsole.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<ResponseResult> {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 = '';}}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com