WDHttp.ets
10.9 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
import http from '@ohos.net.http';
import { BusinessError } from '@ohos.base';
import ArrayList from '@ohos.util.ArrayList';
import {Logger} from 'wdKit';
import { HttpUtils } from '../utils/HttpUtils';
const TAG = 'WDHttp';
export namespace WDHttp {
export enum RequestMethod {
OPTIONS = http.RequestMethod.OPTIONS,
GET = http.RequestMethod.GET,
HEAD = http.RequestMethod.HEAD,
POST = http.RequestMethod.POST,
PUT = http.RequestMethod.PUT,
DELETE = http.RequestMethod.DELETE,
TRACE = http.RequestMethod.TRACE,
CONNECT = http.RequestMethod.CONNECT,
}
export enum HttpParamsType {
STRING,
OBJECT,
ARRAY_BUFFER
}
export interface RequestOptions {
// 请求方法
method?: RequestMethod;
// 请求头
header?: object;
// 读超时时间 单位s 默认60
readTimeout?: number;
// 连接超时时间 单位s 默认60
connectTimeout?: number;
// 请求参数 当请求为get请求时 该参数会自动拼接在url后面
params?: object;
// 请求参数类型 当请求为post时有效
paramsType?: HttpParamsType;
}
export const enum ErrorCode {
// 请求执行(查询)失败
FAILED = -1,
// 请求执行(查询)成功
SUCCESS = http.ResponseCode.OK,
// 业务错误码。。。
}
/**
* ResponseDTO
* 微服务通用返回结构
* http://confluence.cmvideo.cn/confluence/pages/viewpage.action?pageId=4232418
*/
export interface ResponseDTO<T = string> {
// 服务请求响应值/微服务响应状态码”
code: number;
// 服务请求响应说明
message: string;
// 响应结果
body?: T;
// 请求响应时间戳(unix格式)
timeStamp?: number;
// timestamp?: number;
// 返回当前时间戳,格式:yyyyMMddHHmmss,如20230918102124
dataVersion?: string;
}
/**
* ResponseVO
* 基础服务通用返回结构
* 如PUGC错误码:http://confluence.cmvideo.cn/confluence/pages/viewpage.action?pageId=168081524
*/
export interface ResponseVO<T = string> {
// 返回代码,参考附录ResultCode 即(ACCEPTED/SUCCESS/FAILED/REJECTED等)
resultCode: string;
// 返回描述
resultDesc: string;
// 错误码,参考附录和接口中ErrorCode(当resultCode=FAILED才有),如:"ERR_USER_NOTFOUND"
errorCode?: string;
// 业务数据
data?: T;
}
/**
* The Response ResultCode enum.
*/
export const enum ResultCode {
// 请求执行(查询)成功
SUCCESS = 'SUCCESS',
// 请求执行(查询)失败
FAILED = 'FAILED',
// 该请求被拒绝处理,例如参数错误或非法等
REJECTED = 'REJECTED',
// 该请求已经被接收,但是本次同步返回无法知道执行结果
ACCEPTED = 'ACCEPTED',
// 参数错误
// ERR_NOT_VALID_PARAMETERS = 'ERR_NOT_VALID_PARAMETERS'
}
export class Request {
private static globalHeaderProviders: ArrayList<() => Record<string, string>> = new ArrayList();
static addGlobalHeaderProvider(provider: () => Record<string, string>) {
Request.globalHeaderProviders.add(provider)
}
static initHttpHeader() {
Request.addGlobalHeaderProvider(() => {
return HttpUtils.buildHeaders();
})
}
private static makeRequestOptions(options?: RequestOptions): http.HttpRequestOptions {
if (options) {
let op: http.HttpRequestOptions = {};
op.method = options.method!.toString() as http.RequestMethod;
op.header = options.header
op.readTimeout = (options.readTimeout ?? 60) * 1000
op.connectTimeout = (options.connectTimeout ?? 60) * 1000
if (options.method == RequestMethod.POST) {
op.extraData = options.params;
if (options.paramsType == HttpParamsType.STRING) {
op.expectDataType = http.HttpDataType.STRING;
} else if (options.paramsType == HttpParamsType.OBJECT) {
op.expectDataType = http.HttpDataType.OBJECT;
} else if (options.paramsType == HttpParamsType.ARRAY_BUFFER) {
op.expectDataType = http.HttpDataType.ARRAY_BUFFER;
}
} else if (options.method == RequestMethod.PUT) {
// todo
} else if (options.method == RequestMethod.DELETE) {
// todo
}
return op;
}
return {}
}
private static makeUrl(url: string, options?: RequestOptions): string {
if (!options || (options.method && options.method != RequestMethod.GET)) {
return url;
}
if (!options.params) {
return url;
}
let paramStr = "";
if (typeof options.params == "string") {
paramStr = options.params;
} else if (typeof options.params == "object") {
let arr: string[] = [];
Object.entries(options.params).forEach((entry: object) => {
arr.push(`${entry[0]}=${entry[1]}`)
})
if (arr.length == 0) {
return url;
}
paramStr = arr.join("&")
}
if (url.indexOf("?") == -1) {
return url + "?" + paramStr;
} else {
if (url.endsWith("?")) {
return url + paramStr;
} else {
return url + "&" + paramStr;
}
}
}
// 加入泛型限定,返回数据类型为T,
// static request<T = any>(url: string, options: RequestOptions, callback?: AsyncCallback<ResponseDTO<T>>) {
// let httpRequest = http.createHttp();
// if (!options) {
// options = {};
// }
// if (!options.method) {
// options.method = RequestMethod.GET;
// }
// if (!options.header) {
// let header: Record<string, string> = {
// // 'Content-Type': 'text/plain'
// 'Content-Type': 'application/json;charset=utf-8'
// };
// options.header = header
// } else if (!options.header['Content-Type']) {
// options.header['Content-Type'] = 'application/json;charset=utf-8';
// }
//
// Request.globalHeaders.forEach((value, key) => {
// options!.header![key] = value;
// })
// let realUrl = Request.makeUrl(url, options);
// httpRequest.request(realUrl, Request.makeRequestOptions(options), (error, responseData: http.HttpResponse) => {
// if (callback) {
// if (error) {
// callback(error, undefined)
// } else {
// try {
// let response: ResponseDTO<T> = JSON.parse(`${responseData.result}`)
// callback(error, response)
// } catch (err) {
// callback(error, { code: responseData?.responseCode, message: responseData?.result?.toString() })
// }
// }
// }
// })
// }
//
// static get<T = any>(url: string, options: RequestOptions, callback?: AsyncCallback<ResponseDTO<T>>) {
// let op = options ?? {}
// op.method = RequestMethod.GET;
// Request.request<T>(url, op, callback)
// }
//
// static post<T = any>(url: string, options: RequestOptions, callback?: AsyncCallback<ResponseDTO<T>>) {
// let op = options ?? {}
// op.method = RequestMethod.POST;
// Request.request<T>(url, op, callback)
// }
//
// static put<T = any>(url: string, options: RequestOptions, callback?: AsyncCallback<ResponseDTO<T>>) {
// let op = options ?? {}
// op.method = RequestMethod.PUT;
// Request.request<T>(url, op, callback)
// }
//
// static delete<T = any>(url: string, options: RequestOptions, callback?: AsyncCallback<ResponseDTO<T>>) {
// let op = options ?? {}
// op.method = RequestMethod.DELETE;
// Request.request<T>(url, op, callback)
// }
////
static request<T = string>(url: string, options?: RequestOptions): Promise<T> {
let httpRequest = http.createHttp();
if (!options) {
options = {};
}
if (!options.method) {
options.method = RequestMethod.GET;
}
if (!options.header) {
let header: Record<string, string> = {
// 'Content-Type': 'text/plain'
'Content-Type': 'application/json;charset=utf-8'
};
options.header = header
} else if (!options.header['Content-Type']) {
options.header['Content-Type'] = 'application/json;charset=utf-8';
}
let commonHeader: Record<string, string | number> = { };
Request.globalHeaderProviders.forEach((func) => {
let headers = func();
for (const obj of Object.entries(headers)) {
commonHeader[obj[0]] = obj[1];
}
})
let userHeader = options.header as Record<string, string | number>
for (const obj1 of Object.entries(userHeader)) {
commonHeader[obj1[0]] = obj1[1];
}
options.header = commonHeader
let realUrl = Request.makeUrl(url, options);
Logger.info(TAG, `request realUrl: ${realUrl}`);
Logger.info(TAG, `header: ${realUrl}`);
return new Promise<T>((resolve, reject) => {
httpRequest.request(realUrl, Request.makeRequestOptions(options))
.then((responseData: http.HttpResponse) => {
try {
if (responseData.responseCode == http.ResponseCode.OK) {
// todo:待处理JSON.parse只解析目标class中指定的字段
// let response = JSON.parse(`${data}`) as ResponseDTO<T>
let response: T = JSON.parse(`${responseData.result}`)
resolve(response)
} else {
// 返回码不是ok
let responseError: BusinessError = {
code: responseData?.responseCode,
message: responseData?.result?.toString(),
name: '业务错误',
}
reject(responseError)
}
} catch (err) {
// json解析异常
let responseParseError: BusinessError = {
code: responseData?.responseCode,
message: responseData?.result?.toString(),
name: '解析异常',
}
reject(responseParseError)
}
})
.catch((error: BusinessError) => {
reject(error)
})
})
}
static get<T = ResponseDTO<string>>(url: string, options?: RequestOptions): Promise<T> {
let op = options ?? {}
op.method = RequestMethod.GET;
return Request.request<T>(url, op)
}
static post<T = ResponseDTO<string>>(url: string, options?: RequestOptions): Promise<T> {
let op = options ?? {}
op.method = RequestMethod.POST;
return Request.request<T>(url, op)
}
static put<T = ResponseDTO<string>>(url: string, options?: RequestOptions): Promise<T> {
let op = options ?? {}
op.method = RequestMethod.PUT;
return Request.request<T>(url, op)
}
static delete<T = ResponseDTO<string>>(url: string, options?: RequestOptions): Promise<T> {
let op = options ?? {}
op.method = RequestMethod.DELETE;
return Request.request<T>(url, op)
}
}
}