基于axios和Promise的网络框架封装

DevEco Studio 版本:DevEco Studio NEXT Developer Preview2
HarmonyOS API 版本:4.1.0(11)
axios 版本:"@ohos/axios": "^2.2.0"

基于 axios 和 Promise 的网络框架封装

  • Get Post 方式支持
  • http 其他请求方式(method)支持
  • 接口 url 参数封装 和 全局的 baseUrl 设置
  • 超时时间设置
  • 全局 Headers,接口自定义 Headers 和 请求 headers 拦截器封装和实现
  • 请求 params 参数和 data 数据支持
  • post 支持 x-www-form-urlencoded 数据格式
  • 请求结果 Json 数据解析(框架已自动解析)
  • 请求结果流程控制,Promise 封装
  • 请求结果 header 数据解析,服务器时间戳和 session

关键代码 HttpUtil.ets封装如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*
* Copyright (c) 2022 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig, Method } from '@ohos/axios';

import ResponseResult from './ResponseResult';
import logger from '../util/Logger';
import { systemDateTime } from '@kit.BasicServicesKit';
import { HashMap } from '@kit.ArkTS';
import Constant from '../common/Constant';

const TAG: string = "HttpUtil"

const timeout = 20000 // 20s超时
const baseUrl = 'https://xxx.xxx.com'

export function httpDefaultSetting() {

// default settings
axios.defaults.baseURL = baseUrl;
axios.defaults.timeout = timeout;

// default headers
axios.defaults.headers.common['Client-Type'] = 'xxx';
axios.defaults.headers.common['Client-Version'] = '1.0.4';
axios.defaults.headers.common['Os'] = 'hmos';
axios.defaults.headers.common['Token'] = 'xxx';

// for post
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 添加请求拦截器
axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {
return transRequest(config);
}, (error: AxiosError) => {
return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use((response: AxiosResponse) => {
return transResponse(response);
}, (error: AxiosError) => {
return Promise.reject(error);
});
}

/**
* 请在这里处理请求体的拦截器操作逻辑
*
*/
function transRequest(config: InternalAxiosRequestConfig): InternalAxiosRequestConfig {
try {
let millis = systemDateTime.getTime();
config.headers['t'] = millis - Constant.offsetTime; // 同步时间

// 增加验签逻辑
// 验签可以仅在需要的请求中增加验签,通过增加特定的header属性来区分
} finally {
return config;
}
}

/**
* 请在这里处理请求结果的拦截器操作逻辑
*
*/
function transResponse(response: AxiosResponse): AxiosResponse {
try {
let millis = systemDateTime.getTime();
if (lt != 0 && millis - lt < 60000) return response; // 可选,性能优化 1分钟内避免重复处理
lt = millis
let headers: HashMap<string, ESObject> = JSON.parse(JSON.stringify(response.headers));
let t: number = headers['servertimestamp'];
Constant.offsetTime = millis - t;
return response;
} catch (e) {
console.error(e)
return response;
}
}

let lt = 0

/**
* 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 httpGet<D>(url: string, params?: ESObject, headers?: ESObject): Promise<D> {
logger.debug(TAG, "httpGet: ");
return new Promise<D>((resolve: Function, reject: Function) => {
let startTime = systemDateTime.getTime()
axios.get<ResponseResult, AxiosResponse<ResponseResult>, null>(url, {

headers: headers,

// 指定请求超时的毫秒数(0 表示无超时时间)
timeout: timeout, // 超时

// `connectTimeout` 指定请求连接服务器超时的毫秒数(0 表示无超时时间)
// 如果请求连接服务器超过 `connectTimeout` 的时间,请求将被中断
// connectTimeout: 60000, // 文档和代码不一致,代码中无法设置连接超时时间

params: params,
})
.then((response: AxiosResponse<ResponseResult>) => {
let duration = (systemDateTime.getTime() - startTime).toString()
logger.debug(TAG, "httpGet: Success. duration=" + duration);
logger.debug(TAG, "--------------------------------------");
logger.debug(TAG, "config=" + JSON.stringify(response.config));
logger.debug(TAG, "status=" + response.status);
// logger.debug(TAG, "statusText=" + response.statusText); // always empty??
logger.debug(TAG, "headers=" + JSON.stringify(response.headers));
logger.debug(TAG, "data=" + JSON.stringify(response.data));
logger.debug(TAG, "--------------------------------------");
if (isSuccess(response)) {
if (isResultSuccess(response.data)) {
resolve(response.data.data);
} else {
const e: Error = { name: `${response.data.code}`, message: `${response.data.msg}` }
reject(e);
}
} else {
const e: Error = { name: `${response.status}`, message: `${response.statusText}` }
reject(e);
}
})
.catch((reason: AxiosError) => {
logger.error(TAG, JSON.stringify(reason));
reject(reason)
})
});
}


function getRequestFormData(data?: ESObject): string | undefined {
if (data == undefined) return undefined;
let sb = new StringBuilder();
Object.keys(data).forEach((key: string) => {
sb.append(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
})
const formData = sb.build('&');
logger.debug(TAG, "getRequestFormData: formData=" + formData);
return formData;
}

function buildPostRequestHeader(isFormUrlencoded: boolean, headers?: Record<ESObject, ESObject>): Record<ESObject, ESObject> {
if (headers != null) {
headers['Content-Type'] = isFormUrlencoded ? 'application/x-www-form-urlencoded' : 'application/json'
return headers
}
return {
'Content-Type': isFormUrlencoded ? 'application/x-www-form-urlencoded' : 'application/json',
}
}

/**
* Initiates an HTTP request to a given URL.
*
* @param url URL for initiating an HTTP request.
* @param params Params for initiating an HTTP request.
*/
// o: { [s: string]: ESObject }
export function httpPost<D>(url: string, isFormUrlencoded: boolean = true, data?: ESObject, params?: ESObject, headers?: ESObject): Promise<D> {
// logger.debug(TAG, "httpPost: ");
return new Promise<D>((resolve: Function, reject: Function) => {
let startTime = systemDateTime.getTime()


axios.post(url, isFormUrlencoded ? getRequestFormData(data) : data, {
headers: buildPostRequestHeader(isFormUrlencoded, headers),

// 指定请求超时的毫秒数(0 表示无超时时间)
timeout: timeout, // 超时

// `connectTimeout` 指定请求连接服务器超时的毫秒数(0 表示无超时时间)
// 如果请求连接服务器超过 `connectTimeout` 的时间,请求将被中断
// connectTimeout: 60000, // 文档和代码不一致,代码中无法设置连接超时时间

params: params,
})
.then((response: AxiosResponse<ResponseResult>) => {
let duration = (systemDateTime.getTime() - startTime).toString()
logger.debug(TAG, "httpPost: Success. duration=" + duration);
logger.debug(TAG, "--------------------------------------");
logger.debug(TAG, "config=" + JSON.stringify(response.config));
logger.debug(TAG, "status=" + response.status);
// logger.debug(TAG, "statusText=" + response.statusText); // always empty??
logger.debug(TAG, "headers=" + JSON.stringify(response.headers));
logger.debug(TAG, "data=" + JSON.stringify(response.data));
logger.debug(TAG, "--------------------------------------");
if (isSuccess(response)) {
if (isResultSuccess(response.data)) {
resolve(response.data.data);
} else {
const e: Error = { name: `${response.data.code}`, message: `${response.data.msg}` }
reject(e);
}
} else {
const e: Error = { name: `${response.status}`, message: `${response.statusText}` }
reject(e);
}
})
.catch((reason: AxiosError) => {
logger.error(TAG, JSON.stringify(reason));
reject(reason)
})
});
}

/**
* 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 httpRequest<D>(url: string, method?: Method | string, data?: D, config?: AxiosRequestConfig<D>): Promise<ResponseResult> {
// logger.debug(TAG, "httpRequest: ");
return new Promise<ResponseResult>((resolve: Function, reject: Function) => {
let startTime = systemDateTime.getTime()
axios.request<ResponseResult, AxiosResponse<ResponseResult>, D>({
url: url,
method: method,
baseURL: baseUrl,
headers: config?.headers,

// 指定请求超时的毫秒数(0 表示无超时时间)
timeout: timeout, // 超时

// `connectTimeout` 指定请求连接服务器超时的毫秒数(0 表示无超时时间)
// 如果请求连接服务器超过 `connectTimeout` 的时间,请求将被中断
// connectTimeout: 60000, // 文档和代码不一致,代码中无法设置连接超时时间

params: config?.params,
data: data ?? config?.data
})
.then((response: AxiosResponse<ResponseResult>) => {
let duration = (systemDateTime.getTime() - startTime).toString()
logger.debug(TAG, "httpRequest: Success. duration=" + duration);
logger.debug(TAG, "--------------------------------------");
logger.debug(TAG, "config=" + JSON.stringify(response.config));
logger.debug(TAG, "status=" + response.status);
// logger.debug(TAG, "statusText=" + response.statusText); // always empty??
logger.debug(TAG, "headers=" + JSON.stringify(response.headers));
logger.debug(TAG, "data=" + JSON.stringify(response.data));
logger.debug(TAG, "--------------------------------------");
if (isSuccess(response)) {
if (isResultSuccess(response.data)) {
resolve(response.data.data);
} else {
const e: Error = { name: `${response.data.code}`, message: `${response.data.msg}` }
reject(e);
}
} else {
const e: Error = { name: `${response.status}`, message: `${response.statusText}` }
reject(e);
}
})
.catch((reason: AxiosError) => {
logger.error(TAG, JSON.stringify(reason));
reject(reason)
})
});
}

function isSuccess(response: AxiosResponse): boolean {
return response.status >= 200 && response.status < 300
}

function isResultSuccess(result: ResponseResult): boolean {
return result.code == 0
}

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×