httpRequest.ets
2.38 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
import { http } from '@kit.NetworkKit';
const TAG = 'httpRequestInStream'
export class httpRequest {
// 大于5M的下载请求,使用流下载
/**
* 发起HTTP请求以下载图片资源
* @param {string} imageUrl 图片的URL
* @param {Function} onSuccess 成功回调函数
* @param {Function} onError 失败回调函数
*/
public static httpRequestInStream(imageUrl:string, onSuccess:Function, onError:Function) {
// 每一个httpRequest对应一个HTTP请求任务,不可复用
const httpRequest = http.createHttp();
// 订阅HTTP响应头事件
httpRequest.on('headersReceive', (header) => {
// console.info('header: ' + JSON.stringify(header));
});
// 用于订阅HTTP流式响应数据接收事件
let res = new ArrayBuffer(0);
httpRequest.on('dataReceive', (data) => {
const newRes = new ArrayBuffer(res.byteLength + data.byteLength);
const resView = new Uint8Array(newRes);
resView.set(new Uint8Array(res));
resView.set(new Uint8Array(data), res.byteLength);
res = newRes;
// console.info(TAG, 'dataReceive res length: ' + res.byteLength);
});
// 用于订阅HTTP流式响应数据接收完毕事件
httpRequest.on('dataEnd', () => {
if (res instanceof ArrayBuffer) {
// 如果成功,调用onSuccess回调
// console.info(TAG, 'Success in response, data receive end');
onSuccess(res);
} else {
// 如果数据不是ArrayBuffer类型,可以在这里处理异常
// console.error(TAG, 'Unexpected data type:', res);
onError(new Error('Data is not an ArrayBuffer'));
}
// console.info(TAG, 'No more data in response, data receive end');
});
httpRequest.requestInStream(imageUrl, (error, data) => {
if (error) {
// 如果发生错误,取消订阅事件并销毁请求对象
httpRequest.off('headersReceive');
httpRequest.off('dataReceive');
httpRequest.off('dataEnd');
httpRequest.destroy();
// console.error(`http request failed with. Code: ${error.code}, message: ${error.message}`);
// 调用onError回调
onError(error);
return;
}
// 取消订阅事件
httpRequest.off('headersReceive');
httpRequest.off('dataReceive');
httpRequest.off('dataEnd');
// 销毁请求对象
httpRequest.destroy();
});
}
}