中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
封装一个网络请求的公共方法要如何实现
微信扫码分享
import { http } from '@kit.NetworkKit'; import ResponseResult from '../../viewmodel/ResponseResult'; import { promptAction } from '@kit.ArkUI'; const HTTP_READ_TIMEOUT = 10000 const HTTP_CODE_200 = 200 const SERVER_CODE_ERROR = 500 /** * Initiates an HTTP request to a given URL. * * @param url URL for initiating an HTTP request. * @param params Params for initiating an HTTP request. */ export function httpRequestGet(url: string): Promise<ResponseResult> { let httpRequest = http.createHttp(); let responseResult = httpRequest.request(url, { method: http.RequestMethod.GET, readTimeout: HTTP_READ_TIMEOUT, header: { 'Content-Type': 'application/json' }, connectTimeout: HTTP_READ_TIMEOUT, extraData: {} }); let serverData: ResponseResult = new ResponseResult(); // Processes the data and returns. return responseResult.then((value: http.HttpResponse) => { if (value.responseCode === HTTP_CODE_200) { // Obtains the returned data. let result = `${value.result}`; let resultJson: ResponseResult = JSON.parse(result); return resultJson } else { serverData.msg = `网络请求失败,请稍后尝试!${value.responseCode}`; } return serverData; }).catch(() => { serverData.msg = '网络请求失败,请稍后尝试!'; return serverData; }) } export function httpRequestPost(url: string, data?: ESObject): Promise<ResponseResult> { let httpRequest = http.createHttp(); let responseResult = httpRequest.request(url, { method: http.RequestMethod.POST, readTimeout: HTTP_READ_TIMEOUT, header: { 'Content-Type': 'application/json' }, connectTimeout: HTTP_READ_TIMEOUT, extraData: data }); let serverData: ResponseResult = new ResponseResult(); // Processes the data and returns. return responseResult.then((value: http.HttpResponse) => { if (value.responseCode === HTTP_CODE_200) { // Obtains the returned data. let result = `${value.result}`; let resultJson: ResponseResult = JSON.parse(result); serverData.data = resultJson.data; serverData.code = resultJson.code; serverData.msg = resultJson.msg; if (resultJson.code === SERVER_CODE_ERROR) { promptAction.showToast({ message: serverData.msg }) } } else { serverData.msg = `网络请求失败,请稍后尝试!${value.responseCode}`; promptAction.showToast({ message: serverData.msg }) } return serverData; }).catch(() => { serverData.msg = '网络请求失败,请稍后尝试!'; promptAction.showToast({ message: serverData.msg }) return serverData; }) }