1# @ohos.net.http (数据请求) 2 3本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。 4 5> **说明:** 6> 7> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 8## 导入模块 9 10```ts 11import { http } from '@kit.NetworkKit'; 12``` 13 14## 完整示例 15 16**注意:** 关于示例代码中this的说明:在本文档的示例中,通过this.context来获取UIAbilityContext,其中this代表继承自UIAbility的UIAbility实例。如需在页面中使用UIAbilityContext提供的能力,[请参见获取UIAbility的上下文消息](http://gitee.com/openharmony/docs/blob/222f8d93e6f0056409aac096e041df3fdd8ae5ec/zh-cn/application-dev/application-models/uiability-usage.md)。 17 18```ts 19// 引入包名 20import { http } from '@kit.NetworkKit'; 21import { BusinessError } from '@kit.BasicServicesKit'; 22import { common } from '@kit.AbilityKit'; 23 24let context: common.UIAbilityContext = this.getUIContext().getHostContext() as common.UIAbilityContext; 25// 每一个httpRequest对应一个HTTP请求任务,不可复用。 26let httpRequest = http.createHttp(); 27// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息。 28// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ 29httpRequest.on('headersReceive', (header: Object) => { 30 console.info('header: ' + JSON.stringify(header)); 31}); 32 33httpRequest.request(// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定。 34 "EXAMPLE_URL", 35 { 36 method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET。 37 // 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定。 38 extraData: 'data to send', 39 expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型。 40 usingCache: true, // 可选,默认为true。 41 priority: 1, // 可选,默认为1。 42 // 开发者根据自身业务需要添加header字段。 43 header: { 'Accept' : 'application/json' }, 44 readTimeout: 60000, // 可选,默认为60000ms。 45 connectTimeout: 60000, // 可选,默认为60000ms。 46 usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定。 47 usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性。 48 caPath: '/path/to/cacert.pem', // 可选,默认使用系统预设CA证书,自API 10开始支持该属性。 49 clientCert: { // 可选,默认不使用客户端证书,自API 11开始支持该属性。 50 certPath: '/path/to/client.pem', // 默认不使用客户端证书,自API 11开始支持该属性。 51 keyPath: '/path/to/client.key', // 若证书包含Key信息,传入空字符串,自API 11开始支持该属性。 52 certType: http.CertType.PEM, // 可选,默认使用PEM,自API 11开始支持该属性。 53 keyPassword: "passwordToKey" // 可选,输入key文件的密码,自API 11开始支持该属性。 54 }, 55 certificatePinning: [ // 可选,支持证书锁定配置信息的动态设置,自API 12开始支持该属性。 56 { 57 publicKeyHash: 'Pin1', // 由应用传入的证书PIN码,自API 12开始支持该属性。 58 hashAlgorithm: 'SHA-256' // 加密算法,当前仅支持SHA-256,自API 12开始支持该属性。 59 }, { 60 publicKeyHash: 'Pin2', // 由应用传入的证书PIN码,自API 12开始支持该属性。 61 hashAlgorithm: 'SHA-256' // 加密算法,当前仅支持SHA-256,自API 12开始支持该属性。 62 } 63 ], 64 multiFormDataList: [ // 可选,仅当Header中,'content-Type'为'multipart/form-data'时生效,自API 11开始支持该属性。 65 { 66 name: "Part1", // 数据名,自API 11开始支持该属性。 67 contentType: 'text/plain', // 数据类型,自API 11开始支持该属性。 68 data: 'Example data', // 可选,数据内容,自API 11开始支持该属性。 69 remoteFileName: 'example.txt' // 可选,自API 11开始支持该属性。 70 }, { 71 name: "Part2", // 数据名,自API 11开始支持该属性。 72 contentType: 'text/plain', // 数据类型,自API 11开始支持该属性。 73 // data/app/el2/100/base/com.example.myapplication/haps/entry/files/fileName.txt 74 filePath: `${context.filesDir}/fileName.txt`, // 可选,传入文件路径,自API 11开始支持该属性。 75 remoteFileName: 'fileName.txt' // 可选,自API 11开始支持该属性。 76 } 77 ], 78 addressFamily: http.AddressFamily.DEFAULT // 可选,系统默认选择目标域名的IPv4地址或IPv6地址,自API 15开始支持该属性。 79 }, 80 (err: BusinessError, data: http.HttpResponse) => { 81 if (!err) { 82 // data.result为HTTP响应内容,可根据业务需要进行解析。 83 console.info('Result:' + JSON.stringify(data.result)); 84 console.info('code:' + JSON.stringify(data.responseCode)); 85 console.info('type:' + JSON.stringify(data.resultType)); 86 // data.header为HTTP响应头,可根据业务需要进行解析。 87 console.info('header:' + JSON.stringify(data.header)); 88 console.info('cookies:' + JSON.stringify(data.cookies)); // 自API version 8开始支持cookie。 89 // 取消订阅HTTP响应头事件。 90 httpRequest.off('headersReceive'); 91 // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 92 httpRequest.destroy(); 93 } else { 94 console.info('error:' + JSON.stringify(err)); 95 // 取消订阅HTTP响应头事件。 96 httpRequest.off('headersReceive'); 97 // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 98 httpRequest.destroy(); 99 } 100 }); 101``` 102 103> **说明:** 104> console.info()输出的数据中包含换行符会导致数据出现截断现象。 105> 106> 自API 12开始支持接收经过brotli算法压缩的HTTP响应。 107 108## http.createHttp 109 110createHttp(): HttpRequest 111 112创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。 113 114> **说明:** 115> 当该请求使用完毕时,须调用destroy方法主动销毁HttpRequest对象。 116 117**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 118 119**系统能力**:SystemCapability.Communication.NetStack 120 121**返回值:** 122 123| 类型 | 说明 | 124| :---------- | :----------------------------------------------------------- | 125| HttpRequest | 返回一个HttpRequest对象,里面包括request、requestInStream、destroy、on和off方法。 | 126 127**示例:** 128 129```ts 130import { http } from '@kit.NetworkKit'; 131 132let httpRequest = http.createHttp(); 133``` 134 135## HttpRequest 136 137HTTP请求任务。在调用HttpRequest的方法前,需要先通过createHttp()创建一个任务。 138 139### request 140 141request(url: string, callback: AsyncCallback\<HttpResponse\>): void 142 143根据URL地址,发起HTTP网络请求,使用callback方式作为异步方法。 144 145> **说明:** 146> 此接口仅支持数据大小为5M以内的数据接收。 147> 若url包含中文或其他语言,需先调用encodeURL(url)编码,再发起请求。 148 149**需要权限**:ohos.permission.INTERNET 150 151**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 152 153**系统能力**:SystemCapability.Communication.NetStack 154 155**参数:** 156 157| 参数名 | 类型 | 必填 | 说明 | 158| -------- | ---------------------------------------------- | ---- | ---------------------- | 159| url | string | 是 | 发起网络请求的URL地址。 | 160| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | 161 162**错误码:** 163 164| 错误码ID | 错误信息 | 165|---------|----------------------------------------------------------------| 166| 401 | Parameter error. | 167| 201 | Permission denied. | 168| 2300001 | Unsupported protocol. | 169| 2300003 | Invalid URL format or missing URL. | 170| 2300005 | Failed to resolve the proxy name. | 171| 2300006 | Failed to resolve the host name. | 172| 2300007 | Failed to connect to the server. | 173| 2300008 | Invalid server response. | 174| 2300009 | Access to the remote resource denied. | 175| 2300016 | Error in the HTTP2 framing layer. | 176| 2300018 | Transferred a partial file. | 177| 2300023 | Failed to write the received data to the disk or application. | 178| 2300025 | Upload failed. | 179| 2300026 | Failed to open or read local data from the file or application.| 180| 2300027 | Out of memory. | 181| 2300028 | Operation timeout. | 182| 2300047 | The number of redirections reaches the maximum allowed. | 183| 2300052 | The server returned nothing (no header or data). | 184| 2300055 | Failed to send data to the peer. | 185| 2300056 | Failed to receive data from the peer. | 186| 2300058 | Local SSL certificate error. | 187| 2300059 | The specified SSL cipher cannot be used. | 188| 2300060 | Invalid SSL peer certificate or SSH remote key. | 189| 2300061 | Invalid HTTP encoding format. | 190| 2300063 | Maximum file size exceeded. | 191| 2300070 | Remote disk full. | 192| 2300073 | Remote file already exists. | 193| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 194| 2300078 | Remote file not found. | 195| 2300094 | Authentication error. | 196| 2300997 | Cleartext traffic not permitted. | 197| 2300998 | It is not allowed to access this domain. | 198| 2300999 | Unknown error. | 199 200> **错误码说明:** 201> 以上错误码的详细介绍参见[通用错误码](../errorcode-universal.md)和[HTTP错误码](errorcode-net-http.md)。 202> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 203 204**示例:** 205 206```ts 207import { http } from '@kit.NetworkKit'; 208 209let httpRequest = http.createHttp(); 210httpRequest.request("EXAMPLE_URL", (err: Error, data: http.HttpResponse) => { 211 if (!err) { 212 console.info('Result:' + data.result); 213 console.info('code:' + data.responseCode); 214 console.info('type:' + JSON.stringify(data.resultType)); 215 console.info('header:' + JSON.stringify(data.header)); 216 console.info('cookies:' + data.cookies); // 自API version 8开始支持cookie。 217 } else { 218 console.info('error:' + JSON.stringify(err)); 219 } 220}); 221``` 222 223### request 224 225request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void 226 227根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。 228 229> **说明:** 230> 此接口仅支持数据大小为5M以内的数据接收,如果有超过5M的数据接收,需要主动在HttpRequestOptions的maxLimit中进行设置。 231> 232> 如需传入cookies,请开发者自行在参数options中添加。 233 234**需要权限**:ohos.permission.INTERNET 235 236**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 237 238**系统能力**:SystemCapability.Communication.NetStack 239 240**参数:** 241 242| 参数名 | 类型 | 必填 | 说明 | 243| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 244| url | string | 是 | 发起网络请求的URL地址。 | 245| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 | 246| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | 247 248**错误码:** 249 250| 错误码ID | 错误信息 | 251|---------|----------------------------------------------------------------| 252| 401 | Parameter error. | 253| 201 | Permission denied. | 254| 2300001 | Unsupported protocol. | 255| 2300003 | Invalid URL format or missing URL. | 256| 2300005 | Failed to resolve the proxy name. | 257| 2300006 | Failed to resolve the host name. | 258| 2300007 | Failed to connect to the server. | 259| 2300008 | Invalid server response. | 260| 2300009 | Access to the remote resource denied. | 261| 2300016 | Error in the HTTP2 framing layer. | 262| 2300018 | Transferred a partial file. | 263| 2300023 | Failed to write the received data to the disk or application. | 264| 2300025 | Upload failed. | 265| 2300026 | Failed to open or read local data from the file or application.| 266| 2300027 | Out of memory. | 267| 2300028 | Operation timeout. | 268| 2300047 | The number of redirections reaches the maximum allowed. | 269| 2300052 | The server returned nothing (no header or data). | 270| 2300055 | Failed to send data to the peer. | 271| 2300056 | Failed to receive data from the peer. | 272| 2300058 | Local SSL certificate error. | 273| 2300059 | The specified SSL cipher cannot be used. | 274| 2300060 | Invalid SSL peer certificate or SSH remote key. | 275| 2300061 | Invalid HTTP encoding format. | 276| 2300063 | Maximum file size exceeded. | 277| 2300070 | Remote disk full. | 278| 2300073 | Remote file already exists. | 279| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 280| 2300078 | Remote file not found. | 281| 2300094 | Authentication error. | 282| 2300997 | Cleartext traffic not permitted. | 283| 2300998 | It is not allowed to access this domain. | 284| 2300999 | Unknown error. | 285 286> **错误码说明:** 287> 以上错误码的详细介绍参见[通用错误码](../errorcode-universal.md)和[HTTP错误码](errorcode-net-http.md)。 288> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 289 290**示例:** 291 292```ts 293import { http } from '@kit.NetworkKit'; 294 295class Header { 296 public contentType: string; 297 298 constructor(contentType: string) { 299 this.contentType = contentType; 300 } 301} 302 303let httpRequest = http.createHttp(); 304let options: http.HttpRequestOptions = { 305 method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET。 306 // 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定。 307 extraData: 'data to send', 308 expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型。 309 usingCache: true, // 可选,默认为true。 310 priority: 1, // 可选,默认为1。 311 // 开发者根据自身业务需要添加header字段。 312 header: new Header('application/json'), 313 readTimeout: 60000, // 可选,默认为60000ms。 314 connectTimeout: 60000, // 可选,默认为60000ms。 315 usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定。 316 usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性。 317}; 318 319httpRequest.request("EXAMPLE_URL", options, (err: Error, data: http.HttpResponse) => { 320 if (!err) { 321 console.info('Result:' + data.result); 322 console.info('code:' + data.responseCode); 323 console.info('type:' + JSON.stringify(data.resultType)); 324 console.info('header:' + JSON.stringify(data.header)); 325 console.info('cookies:' + data.cookies); // 自API version 8开始支持cookie。 326 } else { 327 console.info('error:' + JSON.stringify(err)); 328 } 329}); 330``` 331 332### request 333 334request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> 335 336根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。 337 338> **说明:** 339> 此接口仅支持数据大小为5M以内的数据接收,如果有超过5M的数据接收,需要主动在HttpRequestOptions的maxLimit中进行设置。 340> 341> 如需传入cookies,请开发者自行在参数options中添加。 342 343**需要权限**:ohos.permission.INTERNET 344 345**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 346 347**系统能力**:SystemCapability.Communication.NetStack 348 349**参数:** 350 351| 参数名 | 类型 | 必填 | 说明 | 352| ------- | ------------------ | ---- | ----------------------------------------------- | 353| url | string | 是 | 发起网络请求的URL地址。 | 354| options | HttpRequestOptions | 否 | 参考[HttpRequestOptions](#httprequestoptions)。 | 355 356**返回值:** 357 358| 类型 | 说明 | 359| :------------------------------------- | :-------------------------------- | 360| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 | 361 362**错误码:** 363 364| 错误码ID | 错误信息 | 365|---------|----------------------------------------------------------------| 366| 401 | Parameter error. | 367| 201 | Permission denied. | 368| 2300001 | Unsupported protocol. | 369| 2300003 | Invalid URL format or missing URL. | 370| 2300005 | Failed to resolve the proxy name. | 371| 2300006 | Failed to resolve the host name. | 372| 2300007 | Failed to connect to the server. | 373| 2300008 | Invalid server response. | 374| 2300009 | Access to the remote resource denied. | 375| 2300016 | Error in the HTTP2 framing layer. | 376| 2300018 | Transferred a partial file. | 377| 2300023 | Failed to write the received data to the disk or application. | 378| 2300025 | Upload failed. | 379| 2300026 | Failed to open or read local data from the file or application.| 380| 2300027 | Out of memory. | 381| 2300028 | Operation timeout. | 382| 2300047 | The number of redirections reaches the maximum allowed. | 383| 2300052 | The server returned nothing (no header or data). | 384| 2300055 | Failed to send data to the peer. | 385| 2300056 | Failed to receive data from the peer. | 386| 2300058 | Local SSL certificate error. | 387| 2300059 | The specified SSL cipher cannot be used. | 388| 2300060 | Invalid SSL peer certificate or SSH remote key. | 389| 2300061 | Invalid HTTP encoding format. | 390| 2300063 | Maximum file size exceeded. | 391| 2300070 | Remote disk full. | 392| 2300073 | Remote file already exists. | 393| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 394| 2300078 | Remote file not found. | 395| 2300094 | Authentication error. | 396| 2300997 | Cleartext traffic not permitted. | 397| 2300998 | It is not allowed to access this domain. | 398| 2300999 | Unknown error. | 399 400> **错误码说明:** 401> 以上错误码的详细介绍参见[通用错误码](../errorcode-universal.md)和[HTTP错误码](errorcode-net-http.md)。 402> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 403 404**示例:** 405 406```ts 407import { http } from '@kit.NetworkKit'; 408 409class Header { 410 public contentType: string; 411 412 constructor(contentType: string) { 413 this.contentType = contentType; 414 } 415} 416 417let httpRequest = http.createHttp(); 418let promise = httpRequest.request("EXAMPLE_URL", { 419 method: http.RequestMethod.GET, 420 connectTimeout: 60000, 421 readTimeout: 60000, 422 header: new Header('application/json') 423}); 424promise.then((data:http.HttpResponse) => { 425 console.info('Result:' + data.result); 426 console.info('code:' + data.responseCode); 427 console.info('type:' + JSON.stringify(data.resultType)); 428 console.info('header:' + JSON.stringify(data.header)); 429 console.info('cookies:' + data.cookies); // 自API version 8开始支持cookie。 430 console.info('header.content-Type:' + data.header); 431 console.info('header.Status-Line:' + data.header); 432}).catch((err:Error) => { 433 console.info('error:' + JSON.stringify(err)); 434}); 435``` 436 437### destroy 438 439destroy(): void 440 441中断请求任务。 442 443**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 444 445**系统能力**:SystemCapability.Communication.NetStack 446 447**示例:** 448 449```ts 450import { http } from '@kit.NetworkKit'; 451let httpRequest = http.createHttp(); 452 453httpRequest.destroy(); 454``` 455 456### requestInStream<sup>10+</sup> 457 458requestInStream(url: string, callback: AsyncCallback\<number\>): void 459 460根据URL地址,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。 461 462**需要权限**:ohos.permission.INTERNET 463 464**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 465 466**系统能力**:SystemCapability.Communication.NetStack 467 468**参数:** 469 470| 参数名 | 类型 | 必填 | 说明 | 471| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 472| url | string | 是 | 发起网络请求的URL地址。 | 473| callback | AsyncCallback\<number\> | 是 | 回调函数。 | 474 475**错误码:** 476 477| 错误码ID | 错误信息 | 478|---------|----------------------------------------------------------------| 479| 401 | Parameter error. | 480| 201 | Permission denied. | 481| 2300001 | Unsupported protocol. | 482| 2300003 | Invalid URL format or missing URL. | 483| 2300005 | Failed to resolve the proxy name. | 484| 2300006 | Failed to resolve the host name. | 485| 2300007 | Failed to connect to the server. | 486| 2300008 | Invalid server response. | 487| 2300009 | Access to the remote resource denied. | 488| 2300016 | Error in the HTTP2 framing layer. | 489| 2300018 | Transferred a partial file. | 490| 2300023 | Failed to write the received data to the disk or application. | 491| 2300025 | Upload failed. | 492| 2300026 | Failed to open or read local data from the file or application.| 493| 2300027 | Out of memory. | 494| 2300028 | Operation timeout. | 495| 2300047 | The number of redirections reaches the maximum allowed. | 496| 2300052 | The server returned nothing (no header or data). | 497| 2300055 | Failed to send data to the peer. | 498| 2300056 | Failed to receive data from the peer. | 499| 2300058 | Local SSL certificate error. | 500| 2300059 | The specified SSL cipher cannot be used. | 501| 2300060 | Invalid SSL peer certificate or SSH remote key. | 502| 2300061 | Invalid HTTP encoding format. | 503| 2300063 | Maximum file size exceeded. | 504| 2300070 | Remote disk full. | 505| 2300073 | Remote file already exists. | 506| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 507| 2300078 | Remote file not found. | 508| 2300094 | Authentication error. | 509| 2300997 | Cleartext traffic not permitted. | 510| 2300998 | It is not allowed to access this domain. | 511| 2300999 | Unknown error. | 512 513> **错误码说明:** 514> 以上错误码的详细介绍参见[通用错误码](../errorcode-universal.md)和[HTTP错误码](errorcode-net-http.md)。 515> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 516 517**示例:** 518 519```ts 520import { http } from '@kit.NetworkKit'; 521import { BusinessError } from '@kit.BasicServicesKit'; 522 523let httpRequest = http.createHttp(); 524httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError, data: number) => { 525 if (!err) { 526 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 527 } else { 528 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 529 } 530}) 531``` 532 533### requestInStream<sup>10+</sup> 534 535requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void 536 537根据URL地址和相关配置项,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。 538 539**需要权限**:ohos.permission.INTERNET 540 541**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 542 543**系统能力**:SystemCapability.Communication.NetStack 544 545**参数:** 546 547| 参数名 | 类型 | 必填 | 说明 | 548| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 549| url | string | 是 | 发起网络请求的URL地址。 | 550| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 | 551| callback | AsyncCallback\<[number](#responsecode)\> | 是 | 回调函数。 | 552 553**错误码:** 554 555| 错误码ID | 错误信息 | 556|---------|----------------------------------------------------------------| 557| 401 | Parameter error. | 558| 201 | Permission denied. | 559| 2300001 | Unsupported protocol. | 560| 2300003 | Invalid URL format or missing URL. | 561| 2300005 | Failed to resolve the proxy name. | 562| 2300006 | Failed to resolve the host name. | 563| 2300007 | Failed to connect to the server. | 564| 2300008 | Invalid server response. | 565| 2300009 | Access to the remote resource denied. | 566| 2300016 | Error in the HTTP2 framing layer. | 567| 2300018 | Transferred a partial file. | 568| 2300023 | Failed to write the received data to the disk or application. | 569| 2300025 | Upload failed. | 570| 2300026 | Failed to open or read local data from the file or application.| 571| 2300027 | Out of memory. | 572| 2300028 | Operation timeout. | 573| 2300047 | The number of redirections reaches the maximum allowed. | 574| 2300052 | The server returned nothing (no header or data). | 575| 2300055 | Failed to send data to the peer. | 576| 2300056 | Failed to receive data from the peer. | 577| 2300058 | Local SSL certificate error. | 578| 2300059 | The specified SSL cipher cannot be used. | 579| 2300060 | Invalid SSL peer certificate or SSH remote key. | 580| 2300061 | Invalid HTTP encoding format. | 581| 2300063 | Maximum file size exceeded. | 582| 2300070 | Remote disk full. | 583| 2300073 | Remote file already exists. | 584| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 585| 2300078 | Remote file not found. | 586| 2300094 | Authentication error. | 587| 2300997 | Cleartext traffic not permitted. | 588| 2300998 | It is not allowed to access this domain. | 589| 2300999 | Unknown error. | 590 591> **错误码说明:** 592> 以上错误码的详细介绍参见[通用错误码](../errorcode-universal.md)和[HTTP错误码](errorcode-net-http.md)。 593> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 594 595**示例:** 596 597```ts 598import { http } from '@kit.NetworkKit'; 599import { BusinessError } from '@kit.BasicServicesKit'; 600 601class Header { 602 public contentType: string; 603 604 constructor(contentType: string) { 605 this.contentType = contentType; 606 } 607} 608 609let httpRequest = http.createHttp(); 610let options: http.HttpRequestOptions = { 611 method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET。 612 // 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定。 613 extraData: 'data to send', 614 expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型。 615 usingCache: true, // 可选,默认为true。 616 priority: 1, // 可选,默认为1。 617 // 开发者根据自身业务需要添加header字段。 618 header: new Header('application/json'), 619 readTimeout: 60000, // 可选,默认为60000ms。 620 connectTimeout: 60000, // 可选,默认为60000ms。 621 usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定。 622 usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性。 623}; 624httpRequest.requestInStream("EXAMPLE_URL", options, (err: BusinessError<void> , data: number) => { 625 if (!err) { 626 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 627 } else { 628 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 629 } 630}) 631``` 632 633### requestInStream<sup>10+</sup> 634 635requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\> 636 637根据URL地址,发起HTTP网络请求并返回流式响应,使用Promise方式作为异步方法。 638 639**需要权限**:ohos.permission.INTERNET 640 641**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 642 643**系统能力**:SystemCapability.Communication.NetStack 644 645**参数:** 646 647| 参数名 | 类型 | 必填 | 说明 | 648| ------- | ------------------ | ---- | ----------------------------------------------- | 649| url | string | 是 | 发起网络请求的URL地址。 | 650| options | HttpRequestOptions | 否 | 参考[HttpRequestOptions](#httprequestoptions)。 | 651 652**返回值:** 653 654| 类型 | 说明 | 655| :------------------------------------- | :-------------------------------- | 656| Promise\<[number](#responsecode)\> | 以Promise形式返回发起请求的结果。 | 657 658**错误码:** 659 660| 错误码ID | 错误信息 | 661|---------|----------------------------------------------------------------| 662| 401 | Parameter error. | 663| 201 | Permission denied. | 664| 2300001 | Unsupported protocol. | 665| 2300003 | Invalid URL format or missing URL. | 666| 2300005 | Failed to resolve the proxy name. | 667| 2300006 | Failed to resolve the host name. | 668| 2300007 | Failed to connect to the server. | 669| 2300008 | Invalid server response. | 670| 2300009 | Access to the remote resource denied. | 671| 2300016 | Error in the HTTP2 framing layer. | 672| 2300018 | Transferred a partial file. | 673| 2300023 | Failed to write the received data to the disk or application. | 674| 2300025 | Upload failed. | 675| 2300026 | Failed to open or read local data from the file or application.| 676| 2300027 | Out of memory. | 677| 2300028 | Operation timeout. | 678| 2300047 | The number of redirections reaches the maximum allowed. | 679| 2300052 | The server returned nothing (no header or data). | 680| 2300055 | Failed to send data to the peer. | 681| 2300056 | Failed to receive data from the peer. | 682| 2300058 | Local SSL certificate error. | 683| 2300059 | The specified SSL cipher cannot be used. | 684| 2300060 | Invalid SSL peer certificate or SSH remote key. | 685| 2300061 | Invalid HTTP encoding format. | 686| 2300063 | Maximum file size exceeded. | 687| 2300070 | Remote disk full. | 688| 2300073 | Remote file already exists. | 689| 2300077 | The SSL CA certificate does not exist or is inaccessible. | 690| 2300078 | Remote file not found. | 691| 2300094 | Authentication error. | 692| 2300997 | Cleartext traffic not permitted. | 693| 2300998 | It is not allowed to access this domain. | 694| 2300999 | Unknown error. | 695 696> **错误码说明:** 697> 以上错误码的详细介绍参见[通用错误码](../errorcode-universal.md)和[HTTP错误码](errorcode-net-http.md)。 698> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 699 700**示例:** 701 702```ts 703import { http } from '@kit.NetworkKit'; 704 705class Header { 706 public contentType: string; 707 708 constructor(contentType: string) { 709 this.contentType = contentType; 710 } 711} 712 713let httpRequest = http.createHttp(); 714let promise = httpRequest.requestInStream("EXAMPLE_URL", { 715 method: http.RequestMethod.GET, 716 connectTimeout: 60000, 717 readTimeout: 60000, 718 header: new Header('application/json') 719}); 720promise.then((data: number) => { 721 console.info("requestInStream OK!" + data); 722}).catch((err: Error) => { 723 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 724}); 725``` 726 727### on("headerReceive")<sup>(deprecated)</sup> 728 729on(type: "headerReceive", callback: AsyncCallback\<Object\>): void 730 731订阅HTTP Response Header 事件。 732 733> **说明:** 734> 此接口已废弃,建议使用[on("headersReceive")<sup>8+</sup>](#onheadersreceive8)替代。 735 736**系统能力**:SystemCapability.Communication.NetStack 737 738**参数:** 739 740| 参数名 | 类型 | 必填 | 说明 | 741| -------- | ----------------------- | ---- | --------------------------------- | 742| type | string | 是 | 订阅的事件类型,'headerReceive'。 | 743| callback | AsyncCallback\<Object\> | 是 | 回调函数。 | 744 745**示例:** 746 747```ts 748import { http } from '@kit.NetworkKit'; 749import { BusinessError } from '@kit.BasicServicesKit'; 750 751let httpRequest = http.createHttp(); 752httpRequest.on("headerReceive", (data: BusinessError) => { 753 console.info("error:" + JSON.stringify(data)); 754}); 755``` 756 757### off("headerReceive")<sup>(deprecated)</sup> 758 759off(type: "headerReceive", callback?: AsyncCallback\<Object\>): void 760 761取消订阅HTTP Response Header 事件。 762 763> **说明:** 764> 765>1. 此接口已废弃,建议使用[off("headersReceive")<sup>8+</sup>](#offheadersreceive8)替代。 766> 767>2. 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 768 769**系统能力**:SystemCapability.Communication.NetStack 770 771**参数:** 772 773| 参数名 | 类型 | 必填 | 说明 | 774| -------- | ----------------------- | ---- | ------------------------------------- | 775| type | string | 是 | 取消订阅的事件类型,'headerReceive'。 | 776| callback | AsyncCallback\<Object\> | 否 | 回调函数。 | 777 778**示例:** 779 780```ts 781import { http } from '@kit.NetworkKit'; 782 783let httpRequest = http.createHttp(); 784httpRequest.off("headerReceive"); 785``` 786 787### on("headersReceive")<sup>8+</sup> 788 789on(type: "headersReceive", callback: Callback\<Object\>): void 790 791订阅HTTP Response Header 事件。 792 793**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 794 795**系统能力**:SystemCapability.Communication.NetStack 796 797**参数:** 798 799| 参数名 | 类型 | 必填 | 说明 | 800| -------- | ------------------ | ---- | ---------------------------------- | 801| type | string | 是 | 订阅的事件类型:'headersReceive'。 | 802| callback | Callback\<Object\> | 是 | 回调函数。 | 803 804**示例:** 805 806```ts 807import { http } from '@kit.NetworkKit'; 808 809let httpRequest = http.createHttp(); 810httpRequest.on("headersReceive", (header: Object) => { 811 console.info("header: " + JSON.stringify(header)); 812}); 813httpRequest.off("headersReceive"); 814``` 815 816### off("headersReceive")<sup>8+</sup> 817 818off(type: "headersReceive", callback?: Callback\<Object\>): void 819 820取消订阅HTTP Response Header 事件。 821 822> **说明:** 823> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 824 825**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 826 827**系统能力**:SystemCapability.Communication.NetStack 828 829**参数:** 830 831| 参数名 | 类型 | 必填 | 说明 | 832| -------- | ------------------ | ---- | -------------------------------------- | 833| type | string | 是 | 取消订阅的事件类型:'headersReceive'。 | 834| callback | Callback\<Object\> | 否 | 回调函数。 | 835 836**示例:** 837 838```ts 839import { http } from '@kit.NetworkKit'; 840 841let httpRequest = http.createHttp(); 842httpRequest.on("headersReceive", (header: Object) => { 843 console.info("header: " + JSON.stringify(header)); 844}); 845httpRequest.off("headersReceive"); 846``` 847 848### once("headersReceive")<sup>8+</sup> 849 850once(type: "headersReceive", callback: Callback\<Object\>): void 851 852订阅HTTP Response Header 事件,只能触发一次。触发之后,订阅器就会被移除。使用callback方式作为异步方法。 853 854**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 855 856**系统能力**:SystemCapability.Communication.NetStack 857 858**参数:** 859 860| 参数名 | 类型 | 必填 | 说明 | 861| -------- | ------------------ | ---- | ---------------------------------- | 862| type | string | 是 | 订阅的事件类型:'headersReceive'。 | 863| callback | Callback\<Object\> | 是 | 回调函数。 | 864 865**示例:** 866 867```ts 868import { http } from '@kit.NetworkKit'; 869 870let httpRequest = http.createHttp(); 871httpRequest.once("headersReceive", (header: Object) => { 872 console.info("header: " + JSON.stringify(header)); 873}); 874``` 875 876### on("dataReceive")<sup>10+</sup> 877 878on(type: "dataReceive", callback: Callback\<ArrayBuffer\>): void 879 880订阅HTTP流式响应数据接收事件。 881 882**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 883 884**系统能力**:SystemCapability.Communication.NetStack 885 886**参数:** 887 888| 参数名 | 类型 | 必填 | 说明 | 889| -------- | ----------------------- | ---- | --------------------------------- | 890| type | string | 是 | 订阅的事件类型,'dataReceive'。 | 891| callback | AsyncCallback\<ArrayBuffer\> | 是 | 回调函数。 | 892 893**示例:** 894 895```ts 896import { http } from '@kit.NetworkKit'; 897 898let httpRequest = http.createHttp(); 899httpRequest.on("dataReceive", (data: ArrayBuffer) => { 900 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 901}); 902httpRequest.off("dataReceive"); 903``` 904 905### off("dataReceive")<sup>10+</sup> 906 907off(type: "dataReceive", callback?: Callback\<ArrayBuffer\>): void 908 909取消订阅HTTP流式响应数据接收事件。 910 911> **说明:** 912> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 913 914**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 915 916**系统能力**:SystemCapability.Communication.NetStack 917 918**参数:** 919 920| 参数名 | 类型 | 必填 | 说明 | 921| -------- | ------------------ | ---- | -------------------------------------- | 922| type | string | 是 | 取消订阅的事件类型:'dataReceive'。 | 923| callback | Callback\<ArrayBuffer\> | 否 | 回调函数。 | 924 925**示例:** 926 927```ts 928import { http } from '@kit.NetworkKit'; 929 930let httpRequest = http.createHttp(); 931httpRequest.on("dataReceive", (data: ArrayBuffer) => { 932 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 933}); 934httpRequest.off("dataReceive"); 935``` 936 937### on("dataEnd")<sup>10+</sup> 938 939on(type: "dataEnd", callback: Callback\<void\>): void 940 941订阅HTTP流式响应数据接收完毕事件。 942 943**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 944 945**系统能力**:SystemCapability.Communication.NetStack 946 947**参数:** 948 949| 参数名 | 类型 | 必填 | 说明 | 950| -------- | ----------------------- | ---- | --------------------------------- | 951| type | string | 是 | 订阅的事件类型,'dataEnd'。 | 952| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 953 954**示例:** 955 956```ts 957import { http } from '@kit.NetworkKit'; 958 959let httpRequest = http.createHttp(); 960httpRequest.on("dataEnd", () => { 961 console.info("Receive dataEnd !"); 962}); 963httpRequest.off("dataEnd"); 964``` 965 966### off("dataEnd")<sup>10+</sup> 967 968off(type: "dataEnd", callback?: Callback\<void\>): void 969 970取消订阅HTTP流式响应数据接收完毕事件。 971 972> **说明:** 973> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 974 975**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 976 977**系统能力**:SystemCapability.Communication.NetStack 978 979**参数:** 980 981| 参数名 | 类型 | 必填 | 说明 | 982| -------- | ------------------ | ---- | -------------------------------------- | 983| type | string | 是 | 取消订阅的事件类型:'dataEnd'。 | 984| callback | Callback\<void\> | 否 | 回调函数。 | 985 986**示例:** 987 988```ts 989import { http } from '@kit.NetworkKit'; 990 991let httpRequest = http.createHttp(); 992httpRequest.on("dataEnd", () => { 993 console.info("Receive dataEnd !"); 994}); 995httpRequest.off("dataEnd"); 996``` 997 998### on('dataReceiveProgress')<sup>10+</sup> 999 1000on(type: 'dataReceiveProgress', callback: Callback\<DataReceiveProgressInfo\>): void 1001 1002订阅HTTP流式响应数据接收进度事件。 1003 1004**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 1005 1006**系统能力**:SystemCapability.Communication.NetStack 1007 1008**参数:** 1009 1010| 参数名 | 类型 | 必填 | 说明 | 1011| -------- | ----------------------- | ---- | --------------------------------- | 1012| type | string | 是 | 订阅的事件类型,'dataReceiveProgress'。 | 1013| callback | AsyncCallback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | 是 | 回调函数。返回数据接收进度信息。 | 1014 1015**示例:** 1016 1017```ts 1018import { http } from '@kit.NetworkKit'; 1019 1020let httpRequest = http.createHttp(); 1021httpRequest.on("dataReceiveProgress", (data: http.DataReceiveProgressInfo) => { 1022 console.info("dataReceiveProgress:" + JSON.stringify(data)); 1023}); 1024httpRequest.off("dataReceiveProgress"); 1025``` 1026 1027### off('dataReceiveProgress')<sup>10+</sup> 1028 1029off(type: 'dataReceiveProgress', callback?: Callback\<DataReceiveProgressInfo\>): void 1030 1031取消订阅HTTP流式响应数据接收进度事件。 1032 1033> **说明:** 1034> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1035 1036**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 1037 1038**系统能力**:SystemCapability.Communication.NetStack 1039 1040**参数:** 1041 1042| 参数名 | 类型 | 必填 | 说明 | 1043| -------- | ------------------ | ---- | -------------------------------------- | 1044| type | string | 是 | 取消订阅的事件类型:'dataReceiveProgress'。 | 1045| callback | Callback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | 否 | 回调函数。 返回数据接收进度信息。 | 1046 1047**示例:** 1048 1049```ts 1050import { http } from '@kit.NetworkKit'; 1051 1052let httpRequest = http.createHttp(); 1053httpRequest.on("dataReceiveProgress", (data: http.DataReceiveProgressInfo) => { 1054 console.info("dataReceiveProgress:" + JSON.stringify(data)); 1055}); 1056httpRequest.off("dataReceiveProgress"); 1057``` 1058 1059### on('dataSendProgress')<sup>11+</sup> 1060 1061on(type: 'dataSendProgress', callback: Callback\<DataSendProgressInfo\>): void 1062 1063订阅HTTP网络请求数据发送进度事件。 1064 1065**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 1066 1067**系统能力**:SystemCapability.Communication.NetStack 1068 1069**参数:** 1070 1071| 参数名 | 类型 | 必填 | 说明 | 1072| -------- | ----------------------- | ---- | --------------------------------- | 1073| type | string | 是 | 订阅的事件类型,'dataSendProgress'。 | 1074| callback | AsyncCallback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | 是 | 回调函数。返回数据发送进度信息。| 1075 1076**示例:** 1077 1078```ts 1079import { http } from '@kit.NetworkKit'; 1080 1081let httpRequest = http.createHttp(); 1082httpRequest.on("dataSendProgress", (data: http.DataSendProgressInfo) => { 1083 console.info("dataSendProgress:" + JSON.stringify(data)); 1084}); 1085httpRequest.off("dataSendProgress"); 1086``` 1087 1088### off('dataSendProgress')<sup>11+</sup> 1089 1090off(type: 'dataSendProgress', callback?: Callback\<DataSendProgressInfo\>): void 1091 1092取消订阅HTTP网络请求数据发送进度事件。 1093 1094> **说明:** 1095> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1096 1097**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 1098 1099**系统能力**:SystemCapability.Communication.NetStack 1100 1101**参数:** 1102 1103| 参数名 | 类型 | 必填 | 说明 | 1104| -------- | ------------------ | ---- | -------------------------------------- | 1105| type | string | 是 | 取消订阅的事件类型:'dataSendProgress'。 | 1106| callback | Callback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | 否 | 回调函数。返回数据接发送进度信息。 | 1107 1108**示例:** 1109 1110```ts 1111import { http } from '@kit.NetworkKit'; 1112 1113let httpRequest = http.createHttp(); 1114httpRequest.on("dataSendProgress", (data: http.DataSendProgressInfo) => { 1115 console.info("dataSendProgress:" + JSON.stringify(data)); 1116}); 1117httpRequest.off("dataSendProgress"); 1118``` 1119 1120## HttpRequestOptions 1121 1122发起请求可选参数的类型和取值范围。 1123 1124**系统能力**:SystemCapability.Communication.NetStack 1125 1126| 名称 | 类型 | 必填 | 说明 | 1127| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 1128| method | [RequestMethod](#requestmethod) | 否 | 请求方式,默认为GET。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1129| extraData | string \| Object \| ArrayBuffer | 否 | 发送请求的额外数据,默认无此字段。<br />1. 当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。<br />(1) 当'content-Type'为'application/x-www-form-urlencoded'时,请求提交的信息主体数据必须在key和value进行URL转码后(encodeURIComponent/encodeURI),按照键值对"key1=value1&key2=value2&key3=value3"的方式进行编码,该字段对应的类型通常为String。<br />(2) 当'content-Type'为'text/xml'时,该字段对应的类型通常为String。<br />(3) 当'content-Type'为'application/json'时,该字段对应的类型通常为Object。<br />(4) 当'content-Type'为'application/octet-stream'时,该字段对应的类型通常为ArrayBuffer。<br />(5) 当'content-Type'为'multipart/form-data'且需上传的字段为文件时,该字段对应的类型通常为ArrayBuffer。<br>以上信息仅供参考,并可能根据具体情况有所不同。<br />2. 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送。ArrayBuffer类型的参数不会做拼接处理。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1130| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型,默认无此字段。如果设置了此参数,系统将优先返回指定的类型。当指定其类型为Object时,最大长度为65536。 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。| 1131| usingCache<sup>9+</sup> | boolean | 否 | 是否使用缓存,默认为true,请求时优先读取缓存。 缓存跟随当前进程生效。新缓存会替换旧缓存;false:不使用缓存。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1132| priority<sup>9+</sup> | number | 否 | http/https请求并发优先级,值越大优先级越高,范围[1,1000],默认为1。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1133| header | Object | 否 | HTTP请求头字段。当请求方式为"POST" "PUT" "DELETE" 或者""时,默认{'content-Type': 'application/json'}, 否则默认{'content-Type': 'application/x-www-form-urlencoded'}。<br />如果head中包含number类型的字段,最大支持int64的整数。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1134| readTimeout | number | 否 | 读取超时时间。单位为毫秒(ms),默认为60000ms。传入值需为uint32_t范围内的整数。<br />设置为0表示不会出现超时情况。 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。| 1135| connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。传入值需为uint32_t范围内的整数。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1136| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | 否 | 使用协议。默认值由系统自动指定。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1137| usingProxy<sup>10+</sup> | boolean \| [HttpProxy](js-apis-net-connection.md#httpproxy10) | 否 | 是否使用HTTP代理,默认为false,不使用代理;true:使用HTTP代理。<br />- 当usingProxy为布尔类型true时,使用默认网络代理。<br />- 当usingProxy为HttpProxy类型时,使用指定网络代理。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1138| caPath<sup>10+</sup> | string | 否 | 如果设置了此参数,系统将使用用户指定路径的CA证书,(开发者需保证该路径下CA证书的可访问性),否则将使用系统预设CA证书。<br />系统预设CA证书位置:/etc/ssl/certs/cacert.pem。证书路径为沙箱映射路径(开发者可通过getContext().filesDir获取应用沙箱路径)。目前仅支持后缀名为.pem的文本格式证书。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1139| resumeFrom<sup>11+</sup> | number | 否 | 用于设置下载起始位置,该参数只能用于GET方法,不要用于其他。HTTP标准(RFC 7233第3.1节)允许服务器忽略范围请求。<br />- 使用HTTP PUT时,不应使用该选项,因为该选项可能与其他选项冲突。<br />- 取值范围是:1~4294967296(4GB),超出范围则不生效。 | 1140| resumeTo<sup>11+</sup> | number | 否 | 用于设置下载结束位置,该参数只能用于GET方法,不要用于其他。HTTP标准(RFC 7233第3.1节)允许服务器忽略范围请求。<br />- 使用HTTP PUT时,不应使用该选项,因为该选项可能与其他选项冲突。<br />- 取值范围是:1~4294967296(4GB),超出范围则不生效。 | 1141| clientCert<sup>11+</sup> | [ClientCert](#clientcert11) | 否 | 支持传输客户端证书。 | 1142| dnsOverHttps<sup>11+</sup> | string | 否 | 设置使用https协议的服务器进行DNS解析。<br />- 参数必须以以下格式进行URL编码:"https:// host:port/path"。 | 1143| dnsServers<sup>11+</sup> | Array\<string\> | 否 | 设置指定的DNS服务器进行DNS解析。<br />- 可以设置多个DNS解析服务器,最多3个服务器。如果有3个以上,只取前3个。<br />- 服务器必须是IPV4或者IPV6地址。 | 1144| maxLimit<sup>11+</sup> | number | 否 | 响应消息的最大字节限制。默认值为5\*1024\*1024,以字节为单位。最大值为100\*1024\*1024,以字节为单位。 | 1145| multiFormDataList<sup>11+</sup> | Array<[MultiFormData](#multiformdata11)> | 否 | 当'content-Type'为'multipart/form-data'时,则上传该字段定义的数据字段表单列表。 | 1146| certificatePinning<sup>12+</sup> | [CertificatePinning](#certificatepinning12) \| CertificatePinning[] | 否 | 支持动态设置证书锁定配置,可以传入单个或多个证书PIN码。 | 1147| addressFamily<sup>15+</sup> | [AddressFamily](#addressfamily15) | 否 | 支持解析目标域名时限定地址类型。 | 1148| remoteValidation<sup>18+</sup> | [RemoteValidation](#remotevalidation18) | 否 | 证书颁发机构(CA),用于验证远程服务器的身份。如果未设置此字段,系统CA将用于验证远程服务器的标识。<br>**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 | 1149| tlsOptions<sup>18+</sup> | [TlsOptions](#tlsoptions18) | 否 | TLS配置。<br>**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 | 1150| serverAuthentication<sup>18+</sup> | [ServerAuthentication](#serverauthentication18) | 否 | 安全连接期间的服务器身份验证配置。默认不认证。<br>**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 | 1151 1152## RequestMethod 1153 1154HTTP 请求方法。 1155 1156**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1157 1158**系统能力**:SystemCapability.Communication.NetStack 1159 1160| 名称 | 值 | 说明 | 1161| :------ | ------- | :------------------ | 1162| OPTIONS | "OPTIONS" | OPTIONS方法描述了目标资源的通信选项。 | 1163| GET | "GET" | GET方法请求指定资源的表示。使用GET的请求应该只检索数据,不应该包含请求内容。 | 1164| HEAD | "HEAD" | HEAD方法请求与GET请求相同的响应,但没有响应主体。 | 1165| POST | "POST" | POST方法将实体提交给指定的资源,通常会导致服务器上的状态更改。 | 1166| PUT | "PUT" | PUT方法将目标资源的所有当前表示替换为请求内容。 | 1167| DELETE | "DELETE" | DELETE方法用于删除指定的资源。 | 1168| TRACE | "TRACE" | TRACE方法沿到达目标资源的路径执行消息环回测试。 | 1169| CONNECT | "CONNECT" | CONNECT方法建立到由目标资源标识的服务器的隧道。 | 1170 1171## ResponseCode 1172 1173发起请求返回的响应码。 1174 1175**系统能力**:SystemCapability.Communication.NetStack 1176 1177| 名称 | 值 | 说明 | 1178| ----------------- | ---- | ------------------------------------------------------------ | 1179| OK | 200 | 请求成功。用于GET与POST请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1180| CREATED | 201 | 已创建。请求成功并已创建新资源。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1181| ACCEPTED | 202 | 已接受。请求已被接受,但未处理完成。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1182| NOT_AUTHORITATIVE | 203 | 非授权信息。请求成功。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1183| NO_CONTENT | 204 | 无内容。服务器成功处理,但未返回内容。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1184| RESET | 205 | 重置内容。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1185| PARTIAL | 206 | 部分内容。服务器成功处理了部分GET请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1186| MULT_CHOICE | 300 | 多种选择。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1187| MOVED_PERM | 301 | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1188| MOVED_TEMP | 302 | 临时移动。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1189| SEE_OTHER | 303 | 查看其它地址。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1190| NOT_MODIFIED | 304 | 未修改。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1191| USE_PROXY | 305 | 使用代理。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1192| BAD_REQUEST | 400 | 客户端请求的语法错误,服务器无法理解。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1193| UNAUTHORIZED | 401 | 请求需要用户的身份认证。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1194| PAYMENT_REQUIRED | 402 | 保留字段,将来使用。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1195| FORBIDDEN | 403 | 服务器理解请求客户端的请求,但是拒绝执行此请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1196| NOT_FOUND | 404 | 服务器无法根据客户端的请求找到资源(网页)。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1197| BAD_METHOD | 405 | 客户端请求中的方法被禁止。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1198| NOT_ACCEPTABLE | 406 | 服务器无法根据客户端请求的内容特性完成请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1199| PROXY_AUTH | 407 | 请求需要代理的身份认证。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1200| CLIENT_TIMEOUT | 408 | 请求超时。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1201| CONFLICT | 409 | 服务器完成客户端的PUT请求时可能返回此代码,服务器处理请求时发生了冲突。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1202| GONE | 410 | 客户端请求的资源已经不存在。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1203| LENGTH_REQUIRED | 411 | 服务器无法处理客户端发送的不带Content-Length的请求信息。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1204| PRECON_FAILED | 412 | 客户端请求信息的先决条件错误。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1205| ENTITY_TOO_LARGE | 413 | 由于请求的实体过大,服务器无法处理,因此拒绝请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1206| REQ_TOO_LONG | 414 | 请求的URI过长(URI通常为网址),服务器无法处理。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1207| UNSUPPORTED_TYPE | 415 | 服务器无法处理请求的格式。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1208| RANGE_NOT_SATISFIABLE<sup>12+</sup> | 416 | 请求范围不符合要求。<br>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 | 1209| INTERNAL_ERROR | 500 | 服务器内部错误,无法完成请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1210| NOT_IMPLEMENTED | 501 | 服务器不支持请求的功能,无法完成请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1211| BAD_GATEWAY | 502 | 充当网关或代理的服务器,从远端服务器接收到了一个无效的请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1212| UNAVAILABLE | 503 | 由于超载或系统维护,服务器暂时无法处理客户端的请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1213| GATEWAY_TIMEOUT | 504 | 充当网关或代理的服务器,未及时从远端服务器获取请求。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1214| VERSION | 505 | 服务器请求的HTTP协议的版本。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1215 1216## HttpResponse 1217 1218request方法回调函数的返回值类型。 1219 1220**系统能力**:SystemCapability.Communication.NetStack 1221 1222| 名称 | 类型 | 必填 | 说明 | 1223| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 1224| result | string \| Object \| ArrayBuffer | 是 | HTTP请求根据响应头中content-type类型返回对应的响应格式内容,若HttpRequestOptions无expectDataType字段,按如下规则返回:<br />- application/json:返回JSON格式的字符串。<br />- application/octet-stream:ArrayBuffer。<br />- image:ArrayBuffer。<br />- 其他:string。<br /> 若HttpRequestOption有expectDataType字段,开发者需传入与服务器返回类型相同的数据类型。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1225| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1226| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1227| header | Object | 是 | 发起HTTP请求返回来的响应头。当前返回的是JSON格式字符串,如需具体字段内容,需开发者自行解析。常见字段及解析方式如下:<br/>- content-type:header['content-type']。<br />- status-line:header['status-line']。<br />- date:header.date/header['date']。<br />- server:header.server/header['server']。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1228| cookies<sup>8+</sup> | string | 是 | 服务器返回的原始cookies。开发者可自行处理。<br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1229| performanceTiming<sup>11+</sup> | [PerformanceTiming](#performancetiming11) | 是 | HTTP请求的各个阶段的耗时。| 1230 1231## ClientCert<sup>11+</sup> 1232 1233客户端证书类型。 1234 1235**系统能力**:SystemCapability.Communication.NetStack 1236 1237| 名称 | 类型 | 必填 | 说明 | 1238| -------- | -------| --- | ----------- | 1239| certPath | string | 是 | 证书路径。 | 1240| certType | [CertType](#certtype11) | 否 | 证书类型,默认是PEM。 | 1241| keyPath | string | 是 | 证书秘钥的路径。 | 1242| keyPassword | string | 否 | 证书秘钥的密码。 | 1243 1244## PerformanceTiming<sup>11+</sup> 1245 1246性能打点(单位:毫秒)。 1247 1248**系统能力**:SystemCapability.Communication.NetStack 1249 1250| 名称 | 类型 | 必填 | 说明 | 1251| ---------- | ------ | ---- | --------------------- | 1252| dnsTiming | number | 是 | 从[request](#request)请求到DNS解析完成耗时。 | 1253| tcpTiming | number | 是 | 从[request](#request)请求到TCP连接完成耗时。 | 1254| tlsTiming | number | 是 | 从[request](#request)请求到TLS连接完成耗时。 | 1255| firstSendTiming | number | 是 | 从[request](#request)请求到开始发送第一个字节的耗时。 | 1256| firstReceiveTiming | number | 是 | 从[request](#request)请求到接收第一个字节的耗时。 | 1257| totalFinishTiming | number | 是 | 从[request](#request)请求到完成请求的耗时。 | 1258| redirectTiming | number | 是 | 从[request](#request)请求到完成所有重定向步骤的耗时。 | 1259| responseHeaderTiming | number | 是 | 从[request](#request)请求到header解析完成的耗时。 | 1260| responseBodyTiming | number | 是 | 从[request](#request)请求到body解析完成的耗时。 | 1261| totalTiming | number | 是 | 从[request](#request)请求回调到应用程序的耗时。 | 1262 1263## DataReceiveProgressInfo<sup>11+</sup> 1264 1265数据接收信息。 1266 1267**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 1268 1269**系统能力**:SystemCapability.Communication.NetStack 1270 1271| 名称 | 类型 | 必填 | 说明 | 1272| ---- | ---- | ---- | ---- | 1273| receiveSize | number | 是 | 已接收的数据量(字节)。 <br>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 | 1274| totalSize| number | 是 | 总共要接收的数据量(字节)。 <br>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。| 1275 1276## DataSendProgressInfo<sup>11+</sup> 1277 1278数据发送信息。 1279 1280**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 1281 1282**系统能力**:SystemCapability.Communication.NetStack 1283 1284### 属性 1285 1286| 名称 | 类型 | 必填 | 说明 | 1287| ---- | ---- | ---- | ---- | 1288| sendSize | number | 是 | 每次发送的数据量(字节)。 | 1289| totalSize | number | 是 | 总共要发送的数据量(字节)。 | 1290 1291## MultiFormData<sup>11+</sup> 1292 1293多部分表单数据的类型。 1294 1295**系统能力**:SystemCapability.Communication.NetStack 1296 1297| 名称 | 类型 | 必填 | 说明 | 1298| ---- | ---- | ---- | ---- | 1299| name | string | 是 | 数据名称。 | 1300| contentType | string | 是 | 数据类型,如'text/plain','image/png', 'image/jpeg', 'audio/mpeg', 'video/mp4'等。 | 1301| remoteFileName | string | 否 | 上传到服务器保存为文件的名称。 | 1302| data | string \| Object \| ArrayBuffer | 否 | 表单数据内容。 | 1303| filePath | string | 否 | 此参数根据文件的内容设置mime部件的正文内容。用于代替data将文件数据设置为数据内容,如果data为空,则必须设置filePath。如果data有值,则filePath不会生效。| 1304 1305## http.createHttpResponseCache<sup>9+</sup> 1306 1307createHttpResponseCache(cacheSize?: number): HttpResponseCache 1308 1309创建一个HttpResponseCache对象,可用于存储HTTP请求的响应数据。对象中可调用flush与delete方法,cacheSize指定缓存大小。 1310 1311**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1312 1313**系统能力**:SystemCapability.Communication.NetStack 1314 1315**参数:** 1316 1317| 参数名 | 类型 | 必填 | 说明 | 1318| -------- | --------------------------------------- | ---- | ---------- | 1319| cacheSize | number | 否 | 缓存大小最大为10\*1024\*1024(10MB),默认最大。 | 1320 1321**返回值:** 1322 1323| 类型 | 说明 | 1324| :---------- | :----------------------------------------------------------- | 1325| [HttpResponseCache](#httpresponsecache9) | 返回一个存储HTTP访问请求响应的对象。 | 1326 1327**示例:** 1328 1329```ts 1330import { http } from '@kit.NetworkKit'; 1331 1332let httpResponseCache = http.createHttpResponseCache(); 1333``` 1334 1335## HttpResponseCache<sup>9+</sup> 1336 1337存储HTTP访问请求响应的对象。在调用HttpResponseCache的方法前,需要先通过[createHttpResponseCache()](#httpcreatehttpresponsecache9)创建一个任务。 1338 1339**响应头中的相应关键字使用** 1340 1341- **`Cache-Control`**:用于指定缓存策略,如`no-cache`, `no-store`, `max-age`, `public`, `private`等。 1342 1343- **`Expires`**:指定资源的过期时间,格式为GMT时间。 1344 1345- **`ETag`**:用于资源版本标识,客户端可以使用`If-None-Match`请求头来验证资源是否已更改。 1346 1347- **`Last-Modified`**:指定资源最后修改时间,客户端可以使用`If-Modified-Since`请求头来验证资源是否已更改。 1348 1349- **`Vary`**:指定哪些请求头的值会影响缓存的响应,用于区分不同的缓存版本。 1350 1351使用这些关键字时,服务器端需要正确配置响应头,客户端则需要根据这些响应头来决定是否使用缓存的资源,以及如何验证资源是否是最新的。正确的缓存策略可以显著提高应用的性能和用户体验。 1352 1353**如何设置Cache-Control头** 1354 1355`Cache-Control`为通用报头,但通常是在服务器端进行的,它允许你定义一个响应资源应该何时、如何被缓存以及缓存多长时间。以下是一些常用的`Cache-Control`指令及其含义: 1356 1357- **`no-cache`**:表示在使用缓存前,必须先去源服务器校验资源的有效性。如果资源未变更,则响应状态码为304(Not Modified),不发送资源内容,使用缓存中的资源。如果资源已经过期,则响应状态码为200(OK),并发送资源内容。 1358 1359- **`no-store`**:表示不允许缓存资源,每次请求都必须从服务器获取资源。 1360 1361- **`max-age`**:指定缓存的最大时间(以秒为单位)。例如,`Cache-Control: max-age=3600`表示缓存的有效期为1小时。 1362 1363- **`public`**:表明响应可以被任何对象(包括:发送请求的客户端,代理服务器等)缓存。 1364 1365- **`private`**:表明响应只能被单个用户缓存,不能作为共享缓存(即代理服务器不能缓存)。 1366 1367- **`must-revalidate`**:表示必须在使用缓存前验证旧资源的状态,并且在缓存过期后,需要重新验证资源。 1368 1369- **`no-transform`**:表示不允许代理服务器修改响应内容。 1370 1371- **`proxy-revalidate`**:与`must-revalidate`类似,但仅适用于共享缓存。 1372 1373- **`s-maxage`**:类似于`max-age`,但仅适用于共享缓存。 1374 1375### flush<sup>9+</sup> 1376 1377flush(callback: AsyncCallback\<void\>): void 1378 1379将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用callback方式作为异步方法。缓存数据包括:响应头(header)、响应体(result)、cookies、请求时间(requestTime)和响应时间(responseTime)。 1380 1381**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1382 1383**系统能力**:SystemCapability.Communication.NetStack 1384 1385**参数:** 1386 1387| 参数名 | 类型 | 必填 | 说明 | 1388| -------- | --------------------------------------- | ---- | ---------- | 1389| callback | AsyncCallback\<void\> | 是 | 回调函数。返回写入结果。 | 1390 1391**示例:** 1392 1393```ts 1394import { http } from '@kit.NetworkKit'; 1395import { BusinessError } from '@kit.BasicServicesKit'; 1396 1397let httpResponseCache = http.createHttpResponseCache(); 1398let httpRequest = http.createHttp(); 1399httpRequest.request("EXAMPLE_URL", (err: BusinessError, data: http.HttpResponse) => { 1400 if (!err) { 1401 httpResponseCache.flush((err: BusinessError) => { 1402 if (err) { 1403 console.error('flush fail'); 1404 } 1405 console.info('flush success'); 1406 }); 1407 httpRequest.destroy(); 1408 } else { 1409 console.error('error:' + JSON.stringify(err)); 1410 // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 1411 httpRequest.destroy(); 1412 } 1413}); 1414``` 1415 1416### flush<sup>9+</sup> 1417 1418flush(): Promise\<void\> 1419 1420将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用Promise方式作为异步方法。 1421 1422**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1423 1424**系统能力**:SystemCapability.Communication.NetStack 1425 1426**返回值:** 1427 1428| 类型 | 说明 | 1429| --------------------------------- | ------------------------------------- | 1430| Promise\<void\> | 以Promise形式返回写入结果。 | 1431 1432**示例:** 1433 1434```ts 1435import { http } from '@kit.NetworkKit'; 1436import { BusinessError } from '@kit.BasicServicesKit'; 1437 1438let httpRequest = http.createHttp(); 1439let httpResponseCache = http.createHttpResponseCache(); 1440let promise = httpRequest.request("EXAMPLE_URL"); 1441 1442promise.then((data: http.HttpResponse) => { 1443 httpResponseCache.flush().then(() => { 1444 console.error('flush success'); 1445 }).catch((err: BusinessError) => { 1446 console.info('flush fail'); 1447 }); 1448}).catch((err: Error) => { 1449 console.error('error:' + JSON.stringify(err)); 1450}); 1451``` 1452 1453### delete<sup>9+</sup> 1454 1455delete(callback: AsyncCallback\<void\>): void 1456 1457禁用缓存并删除其中的数据,使用callback方式作为异步方法。 1458 1459**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1460 1461**系统能力**:SystemCapability.Communication.NetStack 1462 1463**参数:** 1464 1465| 参数名 | 类型 | 必填 | 说明 | 1466| -------- | --------------------------------------- | ---- | ---------- | 1467| callback | AsyncCallback\<void\> | 是 | 回调函数。返回删除结果。| 1468 1469**示例:** 1470 1471```ts 1472import { http } from '@kit.NetworkKit'; 1473import { BusinessError } from '@kit.BasicServicesKit'; 1474 1475let httpRequest = http.createHttp(); 1476httpRequest.request("EXAMPLE_URL").then(data => { 1477 const httpResponseCache = http.createHttpResponseCache(); 1478 httpResponseCache.delete((err: BusinessError) => { 1479 try { 1480 if (err) { 1481 console.error('fail: ' + err); 1482 } else { 1483 console.info('success'); 1484 } 1485 } catch (err) { 1486 console.error('error: ' + err); 1487 } 1488 }); 1489 httpRequest.destroy(); 1490}).catch((error: BusinessError) => { 1491 console.error("errocode" + JSON.stringify(error)); 1492}); 1493``` 1494 1495### delete<sup>9+</sup> 1496 1497delete(): Promise\<void\> 1498 1499禁用缓存并删除其中的数据,使用Promise方式作为异步方法。 1500 1501**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1502 1503**系统能力**:SystemCapability.Communication.NetStack 1504 1505**返回值:** 1506 1507| 类型 | 说明 | 1508| --------------------------------- | ------------------------------------- | 1509| Promise\<void\> | 以Promise形式返回删除结果。 | 1510 1511**示例:** 1512 1513```ts 1514import { http } from '@kit.NetworkKit'; 1515import { BusinessError } from '@kit.BasicServicesKit'; 1516 1517let httpRequest = http.createHttp(); 1518httpRequest.request("EXAMPLE_URL").then(data => { 1519 const httpResponseCache = http.createHttpResponseCache(); 1520 httpResponseCache.delete().then(() => { 1521 console.log("success"); 1522 }).catch((err: BusinessError) => { 1523 console.error("fail"); 1524 }); 1525 httpRequest.destroy(); 1526}).catch((error: BusinessError) => { 1527 console.error("errocode" + JSON.stringify(error)); 1528}); 1529``` 1530 1531## HttpDataType<sup>9+</sup> 1532 1533http的数据类型。 1534 1535**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1536 1537**系统能力**:SystemCapability.Communication.NetStack 1538 1539| 名称 | 值 | 说明 | 1540| ------------------ | -- | ----------- | 1541| STRING | 0 | 字符串类型。 | 1542| OBJECT | 1 | 对象类型。 | 1543| ARRAY_BUFFER | 2 | 二进制数组类型。| 1544 1545## HttpProtocol<sup>9+</sup> 1546 1547http协议版本。 1548 1549**系统能力**:SystemCapability.Communication.NetStack 1550 1551| 名称 | 值 | 说明 | 1552| :-------- | :----------- | :----------- | 1553| HTTP1_1 | 0 | 协议http1.1 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1554| HTTP2 | 1 | 协议http2 <br>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 | 1555| HTTP3<sup>11+</sup> | 2 | 协议http3,若系统或服务器不支持,则使用低版本的http协议请求。<br />- 仅对https的URL生效,http则会请求失败。 | 1556 1557## CertType<sup>11+</sup> 1558 1559证书类型的枚举。 1560 1561**系统能力**:SystemCapability.Communication.NetStack 1562 1563| 名称 | 值 | 说明 | 1564| --- | ------ | ---------- | 1565| PEM | PEM | 证书类型PEM。 | 1566| DER | DER | 证书类型DER。 | 1567| P12 | P12 | 证书类型P12。 | 1568 1569## CertificatePinning<sup>12+</sup> 1570 1571由应用配置的证书。 1572 1573**系统能力**:SystemCapability.Communication.NetStack 1574 1575| 名称 | 类型 | 必填 |说明 | 1576| ------------------ |---- |-- | ----------- | 1577| publicKeyHash | string | 是 |字符串类型的证书PIN码。 | 1578| hashAlgorithm | 'SHA-256' | 是 |加密算法,当前仅支持该算法。 | 1579 1580## HttpProxy<sup>10+</sup> 1581 1582type HttpProxy = connection.HttpProxy 1583 1584网络代理配置信息。 1585 1586**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 1587 1588**系统能力**:SystemCapability.Communication.NetStack 1589 1590| 类型 | 说明 | 1591| ---------------- | --------------------------- | 1592| connection.HttpProxy | 网络代理配置信息。 | 1593 1594## AddressFamily<sup>15+</sup> 1595 1596解析目标域名时限定地址类型的枚举。 1597 1598**系统能力**:SystemCapability.Communication.NetStack 1599 1600| 名称 | 值 | 说明 | 1601| ---------------- | --------------- | --------------------------- | 1602| DEFAULT | CURL_IPRESOLVE_WHATEVER | 设置此选项后,系统将自行选择目标域名的IPv4地址或IPv6地址。 | 1603| ONLY_V4 | CURL_IPRESOLVE_V4 | 设置此选项后,系统仅解析目标域名的IPv4地址,忽略IPv6地址。 | 1604| ONLY_V6 | CURL_IPRESOLVE_V6 | 设置此选项后,系统仅解析目标域名的IPv6地址,忽略IPv4地址。 | 1605 1606## RemoteValidation<sup>18+</sup> 1607 1608type RemoteValidation = 'system' | 'skip' 1609 1610证书颁发机构(CA),用于验证远程服务器的身份,可以通过RemoteValidation配置使用系统CA或跳过验证远程服务器CA。 1611 1612**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1613 1614**系统能力**:SystemCapability.Communication.NetStack 1615 1616| 类型 | 说明 | 1617| ---------------- |---------------| 1618| 'system' | 表示使用系统CA配置验证。 | 1619| 'skip' | 跳过验证远程服务器CA。 | 1620 1621## Credential<sup>18+</sup> 1622 1623会话中服务器身份验证设置所使用的身份验证凭据,包括用户名和密码。 1624 1625**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1626 1627**系统能力**:SystemCapability.Communication.NetStack 1628 1629| 名称 | 类型 | 只读 | 可选 |说明 | 1630| ------------------ |---- |-- | -- |----------- | 1631| username | string | 否 |否 |用于身份验证的用户名。默认值为' '。 | 1632| password | string | 否 |否 |用于身份验证的密码。默认值为' '。 | 1633 1634## ServerAuthentication<sup>18+</sup> 1635 1636HTTP服务器身份验证。 1637 1638**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1639 1640**系统能力**:SystemCapability.Communication.NetStack 1641 1642| 名称 | 类型 | 只读 | 可选 |说明 | 1643| ------------------ |-------------------------------------------------|-------- |------------ |---------------| 1644| credential | [Credential](#credential18) | 否 | 否 |服务器的凭证。默认值为undefined。 | 1645| authenticationType | [AuthenticationType](#authenticationtype18) | 否 | 是 | 服务器的认证类型。如果没有设置,需与服务器协商。 | 1646 1647 1648## TlsConfig<sup>18+</sup> 1649 1650TLS加密版本及套件配置。 1651 1652**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1653 1654**系统能力**:SystemCapability.Communication.NetStack 1655 1656| 名称 | 类型 | 只读 | 可选 |说明 | 1657| ------------------ |---------------------------------|-------- |-------- |---------------| 1658| tlsVersionMin | [TlsVersion](#tlsversion18) | 否 |否 | TLS最低版本号。 | 1659| tlsVersionMax | [TlsVersion](#tlsversion18) | 否 |否 | TLS最高版本号。 | 1660| cipherSuites | [CipherSuite](#ciphersuite18)[] | 否 |是 | 声明加密套件类型的数组。 | 1661 1662## TlsVersion<sup>18+</sup> 1663 1664枚举,TLS版本号。 1665 1666**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1667 1668**系统能力**:SystemCapability.Communication.NetStack 1669 1670| 名称 | 值 | 说明 | 1671|:----------|:--|:-----------| 1672| TLS_V_1_0 | 4 | TLS版本号1.0。 | 1673| TLS_V_1_1 | 5 | TLS版本号1.1。 | 1674| TLS_V_1_2 | 6 | TLS版本号1.2。 | 1675| TLS_V_1_3 | 7 | TLS版本号1.3。 | 1676 1677## TlsOptions<sup>18+</sup> 1678 1679type TlsOptions = 'system' | TlsConfig 1680 1681TLS配置。 1682 1683**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1684 1685**系统能力**:SystemCapability.Communication.NetStack 1686 1687| 类型 | 说明 | 1688|-------------------------------|------------------------------------------------------------------------------------| 1689| 'system' | 表示使用系统的TLS版本,是未进行TLS设置的默认值,值固定为'system'字符串。 | 1690| TlsOptions | 表示使用自定义的TLS版本号和加密套件。 | 1691 1692## RemoteValidation<sup>18+</sup> 1693 1694type RemoteValidation = 'system' | 'skip' 1695 1696验证远程服务器身份的方式。 1697 1698**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1699 1700**系统能力**:SystemCapability.Communication.NetStack 1701 1702| 类型 | 说明 | 1703|-------------------------------|------------------------------------------------------------------------------------| 1704| 'system' | 表示使用系统CA验证远端服务器身份,值固定为'system'字符串,是未配置时的默认值。 | 1705| 'skip' | 表示跳过验证远端服务器身份流程,值固定为'skip'字符串。 | 1706 1707## AuthenticationType<sup>18+</sup> 1708 1709type AuthenticationType = 'basic' | 'ntlm' | 'digest' 1710 1711在会话中的服务器身份验证时可以设置使用不同的身份验证机制。 1712 1713**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1714 1715**系统能力**:SystemCapability.Communication.NetStack 1716 1717|类型 | 说明 | 1718|-------------------------------|----------------------------------------------------------------------------------------------------| 1719| 'basic' | 表示使用基本认证方式,值固定为'basic'字符串。 | 1720| 'ntlm' | 表示使用ntlm认证方式,值固定为'ntlm'字符串。 | 1721| 'digest' | 表示使用摘要认证方式,值固定为'digest'字符串。 | 1722 1723## CipherSuite<sup>18+</sup> 1724 1725type CipherSuite = TlsV13CipherSuite 1726 1727加密套件声明函数。 1728 1729**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1730 1731**系统能力**:SystemCapability.Communication.NetStack 1732 1733| 类型 | 说明 | 1734| ---------------- |-------------------------------------------------------------------| 1735| TlsV13CipherSuite | 表示值的类型为[TlsV13CipherSuite](#tlsv13ciphersuite18)。 | 1736 1737## TlsV13CipherSuite<sup>18+</sup> 1738 1739type TlsV13CipherSuite = TlsV12CipherSuite | TlsV13SpecificCipherSuite 1740 1741TLS1.3的加密套件声明函数,支持TLS1.3版本,兼容TLS1.2版本。 1742 1743**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1744 1745**系统能力**:SystemCapability.Communication.NetStack 1746 1747| 类型 | 说明 | 1748| ---------------- |-------------------------------------------------------------------| 1749| TlsV12CipherSuite | 表示值的类型为[TlsV11CipherSuite](#tlsv11ciphersuite18)。 | 1750| TlsV13SpecificCipherSuite | 表示值的类型为[TlsV13SpecificCipherSuite](#tlsv13specificciphersuite18)。 | 1751 1752## TlsV12CipherSuite<sup>18+</sup> 1753 1754type TlsV12CipherSuite = TlsV11CipherSuite | TlsV12SpecificCipherSuite 1755 1756TLS1.2的加密套件声明函数,支持TLS1.2版本,兼容TLS1.1版本。 1757 1758**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1759 1760**系统能力**:SystemCapability.Communication.NetStack 1761 1762| 类型 | 说明 | 1763| ---------------- |-------------------------------------------------------------------| 1764| TlsV11CipherSuite | 表示值的类型为[TlsV11CipherSuite](#tlsv11ciphersuite18)。 | 1765| TlsV12SpecificCipherSuite | 表示值的类型为[TlsV12SpecificCipherSuite](#tlsv12specificciphersuite18)。 | 1766 1767## TlsV11CipherSuite<sup>18+</sup> 1768 1769type TlsV11CipherSuite = TlsV10CipherSuite 1770 1771TLS1.1的加密套件声明函数,与TLS1.0的加密套件相同。 1772 1773**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1774 1775**系统能力**:SystemCapability.Communication.NetStack 1776 1777| 类型 | 说明 | 1778| ---------------- |---------------------------------------------------| 1779| TlsV10CipherSuite | 表示值的类型为[TlsV10CipherSuite](#tlsv10ciphersuite18)。 | 1780 1781## TlsV10CipherSuite<sup>18+</sup> 1782 1783type TlsV10CipherSuite = TlsV10SpecificCipherSuite 1784 1785TLS1.0的加密套件声明函数。 1786 1787**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1788 1789**系统能力**:SystemCapability.Communication.NetStack 1790 1791| 类型 | 说明 | 1792| ---------------- |-------------------------------------------------------------------| 1793| TlsV10SpecificCipherSuite | 表示值的类型为[TlsV10SpecificCipherSuite](#tlsv10specificciphersuite18)。 | 1794 1795## TlsV13SpecificCipherSuite<sup>18+</sup> 1796 1797type TlsV13SpecificCipherSuite = 'TLS_AES_128_GCM_SHA256' | 'TLS_AES_256_GCM_SHA384' | 'TLS_CHACHA20_POLY1305_SHA256' 1798 1799TLS1.3及以上版本支持的加密套件。 1800 1801**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1802 1803**系统能力**:SystemCapability.Communication.NetStack 1804 1805| 类型 | 说明 | 1806| ---------------- |------| 1807| 'TLS_AES_128_GCM_SHA256' | 表示值的类型为字符串,可取'TLS_AES_128_GCM_SHA256'。 | 1808| 'TLS_AES_256_GCM_SHA384' | 表示值的类型为字符串,可取'TLS_AES_256_GCM_SHA384'。 | 1809| 'TLS_CHACHA20_POLY1305_SHA256' | 表示值的类型为字符串,可取'TLS_CHACHA20_POLY1305_SHA256'。 | 1810 1811## TlsV12SpecificCipherSuite<sup>18+</sup> 1812 1813type TlsV12SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | 1814'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | 1815'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | 1816'TLS_RSA_WITH_AES_128_GCM_SHA256' | 'TLS_RSA_WITH_AES_256_GCM_SHA384' 1817 1818TLS1.2及以上版本支持的加密套件。 1819 1820**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1821 1822**系统能力**:SystemCapability.Communication.NetStack 1823 1824| 类型 | 说明 | 1825| ---------------- |------| 1826| 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | 表示值的类型为字符串,可取'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256'。 | 1827| 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | 表示值的类型为字符串,可取'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256'。 | 1828| 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | 表示值的类型为字符串,可取'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384'。 | 1829| 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | 表示值的类型为字符串,可取'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384'。 | 1830| 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | 表示值的类型为字符串,可取'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256'。 | 1831| 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | 表示值的类型为字符串,可取'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256'。 | 1832| 'TLS_RSA_WITH_AES_128_GCM_SHA256' | 表示值的类型为字符串,可取'TLS_RSA_WITH_AES_128_GCM_SHA256'。 | 1833| 'TLS_RSA_WITH_AES_256_GCM_SHA384' | 表示值的类型为字符串,可取'TLS_RSA_WITH_AES_256_GCM_SHA384'。 | 1834 1835## TlsV10SpecificCipherSuite<sup>18+</sup> 1836 1837type TlsV10SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | 1838'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_AES_128_CBC_SHA' | 1839'TLS_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_3DES_EDE_CBC_SHA' 1840 1841TLS1.0及以上版本支持的加密套件。 1842 1843**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。 1844 1845**系统能力**:SystemCapability.Communication.NetStack 1846 1847| 类型 | 说明 | 1848| ---------------- |------| 1849| 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | 表示值的类型为字符串,可取'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA'。 | 1850| 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | 表示值的类型为字符串,可取'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA'。 | 1851| 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | 表示值的类型为字符串,可取'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA'。 | 1852| 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | 表示值的类型为字符串,可取'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA'。 | 1853| 'TLS_RSA_WITH_AES_128_CBC_SHA' | 表示值的类型为字符串,可取'TLS_RSA_WITH_AES_128_CBC_SHA'。 | 1854| 'TLS_RSA_WITH_AES_256_CBC_SHA' | 表示值的类型为字符串,可取'TLS_RSA_WITH_AES_256_CBC_SHA'。 | 1855| 'TLS_RSA_WITH_3DES_EDE_CBC_SHA' | 表示值的类型为字符串,可取'TLS_RSA_WITH_3DES_EDE_CBC_SHA'。 | 1856