鸿蒙OS ArkUI 封装接口网络请求 – 小白篇
根据官方文档自己又稍微改了一部分,因为写法还比较不太习惯可能封装的比较简陋,但是能用。
后边如果对技术了解更多的话可能会再出一篇进阶的然后增加点修改
首先的思路是要创建一个http的访问,下边是 代码片
。
HttpUtil.ets
import http from '@ohos.net.http'; //引入官方提供的http请求包
//下边这个引用是自定义了一些返回体和状态的代码
import { CommonConstants as Const, ContentType,ResponseResult } from '../common/constants/CommonConstants';';
/**
* @param url 接口请求地址 例如/login
* @param method 请求类型
* @param params 参数 (可选项)
*/
export function httpRequest(url: string,method:http.RequestMethod,params?:any): Promise<ResponseResult> {
//创建一个请求
let httpRequest = http.createHttp();
//拼接请求接口地址
//Const.SERVER 这个是被抽离出去的你的http:xxx.com地址
let responseResult = httpRequest.request(`${Const.SERVER}`+url, {
method: method,// 请求方式 get post delete put 这个需要自己去做
readTimeout: Const.HTTP_READ_TIMEOUT,
header: {
'Content-Type': ContentType.JSON // 请求头
},
connectTimeout: Const.HTTP_READ_TIMEOUT,
// 如果是POST请求就可以直接传第三个参数 如果是get 那就需要在URL传递进来前拼接好
// ps:我没想好get怎么封装
extraData: params
});
let serverData: ResponseResult = new ResponseResult();
// 处理返回数据 下边可以根据自己业务逻辑自己处理
return responseResult.then((value: http.HttpResponse) => {
if (value.responseCode === Const.HTTP_CODE_200) {
let result = `${value.result}`;
let resultJson: ResponseResult = JSON.parse(result);
if (resultJson.code === Const.SERVER_CODE_SUCCESS) {
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;
})
}
CommonConstants.ets
export class CommonConstants {
static readonly SERVER: string = 'http://xxx:8888';
static readonly POST_LOGIN: string = '/login';
/**
* 接口返回状态码
*/
static readonly SERVER_CODE_SUCCESS: number = 0;
/**
* 请求成功状态码
*/
static readonly HTTP_CODE_200: number = 200;
/**
* 超时时间
*/
static readonly HTTP_READ_TIMEOUT: number = 10000;
}
/**
* 请求头
*/
export const enum ContentType {
JSON = 'application/json'
}
/**
* 请求类型
*/
export enum RequestMethod {
OPTIONS = "OPTIONS",
GET = "GET",
HEAD = "HEAD",
POST = "POST",
PUT = "PUT",
DELETE = "DELETE",
TRACE = "TRACE",
CONNECT = "CONNECT"
}
/**
* 请求返回体
*/
export class ResponseResult {
code: number;
msg: string | Resource;
data: any;
constructor() {
this.code = 10086;
this.msg = '';
this.data = '';
}
}
实际使用
//引入你定义好的方法和返回
import {CommonConstants as Const,ResponseResult,RequestMethod} from '../common/constants/CommonConstants';
import { httpRequest } from '../Utils/HttpUtil';
Login():void {//例如登录接口 POST请求
httpRequest(Const.POST_LOGIN,RequestMethod.POST,{'account':'你的账号','password':'你的密码'}).then((data: ResponseResult) => {
if (data.code === Const.SERVER_CODE_SUCCESS) {
Logger.error('rescueLogin failed', data.data);
// resolve(data.data);
} else {
Logger.info('rescueLogin errorcode', JSON.stringify(data));
}
}).catch((err: Error) => {
Logger.error('rescueLogin catch', JSON.stringify(err));
});
//例如登录接口 GET请求
let url:string = Const.POST_LOGIN+`?account=${this.account}&password=${this.password}`
httpRequest(url,RequestMethod.GET).then((data: ResponseResult) => {
if (data.code === Const.SERVER_CODE_SUCCESS) {
Logger.error('rescueLogin failed', data.data);
// resolve(data.data);
} else {
Logger.info('rescueLogin errorcode', JSON.stringify(data));
}
}).catch((err: Error) => {
Logger.error('rescueLogin catch', JSON.stringify(err));
});
}