1/* 2 * Copyright (c) 2022-2025 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16import http from '@ohos.net.http' 17 18class Http { 19 url: string 20 extraData: Object 21 options: http.HttpRequestOptions 22 23 constructor() { 24 this.url = '' 25 this.options = { 26 method: http.RequestMethod.GET, 27 extraData: this.extraData, 28 header: { 'Content-Type': 'application/json' }, 29 readTimeout: 50000, 30 connectTimeout: 50000 31 } 32 } 33 34 setUrl(url: string) { 35 this.url = url 36 } 37 38 setMethod(method: string) { 39 switch (method) { 40 case 'GET': 41 this.options.method = http.RequestMethod.GET; 42 break 43 case 'HEAD': 44 this.options.method = http.RequestMethod.HEAD; 45 break 46 case 'OPTIONS': 47 this.options.method = http.RequestMethod.OPTIONS; 48 break 49 case 'TRACE': 50 this.options.method = http.RequestMethod.TRACE; 51 break 52 case 'DELETE': 53 this.options.method = http.RequestMethod.DELETE; 54 break 55 case 'POST': 56 this.options.method = http.RequestMethod.POST; 57 break 58 case 'PUT': 59 this.options.method = http.RequestMethod.PUT; 60 break 61 case 'CONNECT': 62 this.options.method = http.RequestMethod.CONNECT; 63 break 64 default: 65 this.options.method = http.RequestMethod.GET; 66 break 67 } 68 } 69 70 setExtraData(extraData: Object) { 71 this.options.extraData = extraData 72 } 73 74 setOptions(option: Object) { 75 this.options = option 76 } 77 78 setList(list: number[], flag: number) { 79 list = [] 80 for (let i = 0; i < flag; i++) { 81 list[i] = i 82 } 83 return list 84 } 85 86 setParameter(keys: string[], values: string[]) { 87 let result = {} 88 for (let i = 0; i <= keys.length - 1; i++) { 89 let key = keys[i] 90 let value = values[i] 91 result[key] = value 92 } 93 return result 94 } 95 96 async request() { 97 let httpRequest = http.createHttp() 98 httpRequest.on('dataReceive', function (data) { 99 AppStorage.setOrCreate('dataLength', data.byteLength); 100 console.info('[ Demo dataReceive ] ReceivedDataLength: ' + data.byteLength); 101 }); 102 httpRequest.on('dataReceiveProgress', function (data) { 103 AppStorage.setOrCreate('receiveSize', data.receiveSize); 104 AppStorage.setOrCreate('totalSize', data.totalSize); 105 console.info('[ Demo dataProgress ] ReceivedSize: ' + data.receiveSize + ' TotalSize: ' + data.totalSize); 106 }); 107 httpRequest.requestInStream(this.url, this.options); 108 } 109} 110 111export default new Http()