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## 导入模块 11 12```ts 13import http from '@ohos.net.http'; 14``` 15 16## 完整示例 17 18```ts 19// 引入包名 20import http from '@ohos.net.http'; 21import { BusinessError } from '@ohos.base'; 22 23// 每一个httpRequest对应一个HTTP请求任务,不可复用 24let httpRequest = http.createHttp(); 25// 用于订阅HTTP响应头,此接口会比request请求先返回。可以根据业务需要订阅此消息 26// 从API 8开始,使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+ 27httpRequest.on('headersReceive', (header: Object) => { 28 console.info('header: ' + JSON.stringify(header)); 29}); 30 31class ExtraData { 32 public data: string; 33 34 constructor(data: string) { 35 this.data = data; 36 } 37} 38 39class Header { 40 public contentType: string; 41 42 constructor(contentType: string) { 43 this.contentType = contentType; 44 } 45} 46 47httpRequest.request(// 填写HTTP请求的URL地址,可以带参数也可以不带参数。URL地址需要开发者自定义。请求的参数可以在extraData中指定 48 "EXAMPLE_URL", 49 { 50 method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET 51 // 当使用POST请求时此字段用于传递内容 52 extraData: new ExtraData('data to send'), 53 expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型 54 usingCache: true, // 可选,默认为true 55 priority: 1, // 可选,默认为1 56 // 开发者根据自身业务需要添加header字段 57 header: new Header('application/json'), 58 readTimeout: 60000, // 可选,默认为60000ms 59 connectTimeout: 60000, // 可选,默认为60000ms 60 usingProtocol: http.HttpProtocol.HTTP1_1, // 可选,协议类型默认值由系统自动指定 61 usingProxy: false, //可选,默认不使用网络代理,自API 10开始支持该属性 62 caPath: '/path/to/cacert.pem', // 可选,默认使用系统预设CA证书,自API 10开始支持该属性 63 clientCert: { // 可选,默认不使用客户端证书,自API 11开始支持该属性 64 certPath: '/path/to/client.pem', // 默认不使用客户端证书,自API 11开始支持该属性 65 keyPath: '/path/to/client.key', // 若证书包含Key信息,传入空字符串,自API 11开始支持该属性 66 certType: http.CertType.PEM, // 可选,默认使用PEM,自API 11开始支持该属性 67 keyPassword: "passwordToKey" // 可选,输入key文件的密码,自API 11开始支持该属性 68 }, 69 multiFormDataList: [ // 可选,仅当Header中,'content-Type'为'multipart/form-data'时生效,自API 11开始支持该属性 70 { 71 name: "Part1", // 数据名,自API 11开始支持该属性 72 contentType: 'text/plain', // 数据类型,自API 11开始支持该属性 73 data: 'Example data', // 可选,数据内容,自API 11开始支持该属性 74 remoteFileName: 'example.txt' // 可选,自API 11开始支持该属性 75 }, { 76 name: "Part2", // 数据名,自API 11开始支持该属性 77 contentType: 'text/plain', // 数据类型,自API 11开始支持该属性 78 // data/app/el2/100/base/com.example.myapplication/haps/entry/files/fileName.txt 79 filePath: `${getContext(this).filesDir}/fileName.txt`, // 可选,传入文件路径,自API 11开始支持该属性 80 remoteFileName: 'fileName.txt' // 可选,自API 11开始支持该属性 81 } 82 ] 83 }, 84 (err: BusinessError, data: http.HttpResponse) => { 85 if (!err) { 86 // data.result为HTTP响应内容,可根据业务需要进行解析 87 console.info('Result:' + JSON.stringify(data.result)); 88 console.info('code:' + JSON.stringify(data.responseCode)); 89 console.info('type:' + JSON.stringify(data.resultType)); 90 // data.header为HTTP响应头,可根据业务需要进行解析 91 console.info('header:' + JSON.stringify(data.header)); 92 console.info('cookies:' + JSON.stringify(data.cookies)); // 自API version 8开始支持cookie 93 // 取消订阅HTTP响应头事件 94 httpRequest.off('headersReceive'); 95 // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 96 httpRequest.destroy(); 97 } else { 98 console.info('error:' + JSON.stringify(err)); 99 // 取消订阅HTTP响应头事件 100 httpRequest.off('headersReceive'); 101 // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 102 httpRequest.destroy(); 103 } 104 }); 105``` 106 107> **说明:** 108> console.info()输出的数据中包含换行符会导致数据出现截断现象。 109 110## http.createHttp 111 112createHttp(): HttpRequest 113 114创建一个HTTP请求,里面包括发起请求、中断请求、订阅/取消订阅HTTP Response Header事件。每一个HttpRequest对象对应一个HTTP请求。如需发起多个HTTP请求,须为每个HTTP请求创建对应HttpRequest对象。 115 116> **说明:** 117> 当该请求使用完毕时,须调用destroy方法主动销毁HttpRequest对象。 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 '@ohos.net.http'; 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 148**需要权限**:ohos.permission.INTERNET 149 150**系统能力**:SystemCapability.Communication.NetStack 151 152**参数:** 153 154| 参数名 | 类型 | 必填 | 说明 | 155| -------- | ---------------------------------------------- | ---- | ---------------------- | 156| url | string | 是 | 发起网络请求的URL地址。 | 157| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | 158 159**错误码:** 160 161| 错误码ID | 错误信息 | 162|---------|-------------------------------------------------------| 163| 401 | Parameter error. | 164| 201 | Permission denied. | 165| 2300001 | Unsupported protocol. | 166| 2300003 | URL using bad/illegal format or missing URL. | 167| 2300005 | Couldn't resolve proxy name. | 168| 2300006 | Couldn't resolve host name. | 169| 2300007 | Couldn't connect to server. | 170| 2300008 | Weird server reply. | 171| 2300009 | Access denied to remote resource. | 172| 2300016 | Error in the HTTP2 framing layer. | 173| 2300018 | Transferred a partial file. | 174| 2300023 | Failed writing received data to disk/application. | 175| 2300025 | Upload failed. | 176| 2300026 | Failed to open/read local data from file/application. | 177| 2300027 | Out of memory. | 178| 2300028 | Timeout was reached. | 179| 2300047 | Number of redirects hit maximum amount. | 180| 2300052 | Server returned nothing (no headers, no data). | 181| 2300055 | Failed sending data to the peer. | 182| 2300056 | Failure when receiving data from the peer. | 183| 2300058 | Problem with the local SSL certificate. | 184| 2300059 | Couldn't use specified SSL cipher. | 185| 2300060 | SSL peer certificate or SSH remote key was not OK. | 186| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 187| 2300063 | Maximum file size exceeded. | 188| 2300070 | Disk full or allocation exceeded. | 189| 2300073 | Remote file already exists. | 190| 2300077 | Problem with the SSL CA cert (path? access rights?). | 191| 2300078 | Remote file not found. | 192| 2300094 | An authentication function returned an error. | 193| 2300999 | Unknown Other Error. | 194 195> **错误码说明:** 196> 以上错误码的详细介绍参见[HTTP错误码](errorcode-net-http.md)。 197> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 198 199**示例:** 200 201```ts 202import http from '@ohos.net.http'; 203 204let httpRequest = http.createHttp(); 205httpRequest.request("EXAMPLE_URL", (err: Error, data: http.HttpResponse) => { 206 if (!err) { 207 console.info('Result:' + data.result); 208 console.info('code:' + data.responseCode); 209 console.info('type:' + JSON.stringify(data.resultType)); 210 console.info('header:' + JSON.stringify(data.header)); 211 console.info('cookies:' + data.cookies); // 自API version 8开始支持cookie 212 } else { 213 console.info('error:' + JSON.stringify(err)); 214 } 215}); 216``` 217 218### request 219 220request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpResponse\>):void 221 222根据URL地址和相关配置项,发起HTTP网络请求,使用callback方式作为异步方法。 223 224> **说明:** 225> 此接口仅支持数据大小为5M以内的数据接收。 226 227**需要权限**:ohos.permission.INTERNET 228 229**系统能力**:SystemCapability.Communication.NetStack 230 231**参数:** 232 233| 参数名 | 类型 | 必填 | 说明 | 234| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 235| url | string | 是 | 发起网络请求的URL地址。 | 236| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 | 237| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | 是 | 回调函数。 | 238 239**错误码:** 240 241| 错误码ID | 错误信息 | 242|---------|-------------------------------------------------------| 243| 401 | Parameter error. | 244| 201 | Permission denied. | 245| 2300001 | Unsupported protocol. | 246| 2300003 | URL using bad/illegal format or missing URL. | 247| 2300005 | Couldn't resolve proxy name. | 248| 2300006 | Couldn't resolve host name. | 249| 2300007 | Couldn't connect to server. | 250| 2300008 | Weird server reply. | 251| 2300009 | Access denied to remote resource. | 252| 2300016 | Error in the HTTP2 framing layer. | 253| 2300018 | Transferred a partial file. | 254| 2300023 | Failed writing received data to disk/application. | 255| 2300025 | Upload failed. | 256| 2300026 | Failed to open/read local data from file/application. | 257| 2300027 | Out of memory. | 258| 2300028 | Timeout was reached. | 259| 2300047 | Number of redirects hit maximum amount. | 260| 2300052 | Server returned nothing (no headers, no data). | 261| 2300055 | Failed sending data to the peer. | 262| 2300056 | Failure when receiving data from the peer. | 263| 2300058 | Problem with the local SSL certificate. | 264| 2300059 | Couldn't use specified SSL cipher. | 265| 2300060 | SSL peer certificate or SSH remote key was not OK. | 266| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 267| 2300063 | Maximum file size exceeded. | 268| 2300070 | Disk full or allocation exceeded. | 269| 2300073 | Remote file already exists. | 270| 2300077 | Problem with the SSL CA cert (path? access rights?). | 271| 2300078 | Remote file not found. | 272| 2300094 | An authentication function returned an error. | 273| 2300999 | Unknown Other Error. | 274 275> **错误码说明:** 276> 以上错误码的详细介绍参见[HTTP错误码](errorcode-net-http.md)。 277> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 278 279**示例:** 280 281```ts 282import http from '@ohos.net.http'; 283 284class Header { 285 public contentType: string; 286 287 constructor(contentType: string) { 288 this.contentType = contentType; 289 } 290} 291 292let httpRequest = http.createHttp(); 293let promise = httpRequest.request("EXAMPLE_URL", { 294 method: http.RequestMethod.GET, 295 connectTimeout: 60000, 296 readTimeout: 60000, 297 header: new Header('application/json') 298}); 299 300promise.then((data:http.HttpResponse) => { 301 console.info('Result:' + data.result); 302 console.info('code:' + data.responseCode); 303 console.info('type:' + JSON.stringify(data.resultType)); 304 console.info('header:' + JSON.stringify(data.header)); 305 console.info('cookies:' + data.cookies); // 自API version 8开始支持cookie 306 console.info('header.content-Type:' + data.header); 307 console.info('header.Status-Line:' + data.header); 308 309}).catch((err:Error) => { 310 console.info('error:' + JSON.stringify(err)); 311}); 312``` 313 314### request 315 316request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\> 317 318根据URL地址,发起HTTP网络请求,使用Promise方式作为异步方法。 319 320> **说明:** 321> 此接口仅支持数据大小为5M以内的数据接收。 322 323**需要权限**:ohos.permission.INTERNET 324 325**系统能力**:SystemCapability.Communication.NetStack 326 327**参数:** 328 329| 参数名 | 类型 | 必填 | 说明 | 330| ------- | ------------------ | ---- | ----------------------------------------------- | 331| url | string | 是 | 发起网络请求的URL地址。 | 332| options | HttpRequestOptions | 否 | 参考[HttpRequestOptions](#httprequestoptions)。 | 333 334**返回值:** 335 336| 类型 | 说明 | 337| :------------------------------------- | :-------------------------------- | 338| Promise<[HttpResponse](#httpresponse)> | 以Promise形式返回发起请求的结果。 | 339 340**错误码:** 341 342| 错误码ID | 错误信息 | 343|---------|-------------------------------------------------------| 344| 401 | Parameter error. | 345| 201 | Permission denied. | 346| 2300001 | Unsupported protocol. | 347| 2300003 | URL using bad/illegal format or missing URL. | 348| 2300005 | Couldn't resolve proxy name. | 349| 2300006 | Couldn't resolve host name. | 350| 2300007 | Couldn't connect to server. | 351| 2300008 | Weird server reply. | 352| 2300009 | Access denied to remote resource. | 353| 2300016 | Error in the HTTP2 framing layer. | 354| 2300018 | Transferred a partial file. | 355| 2300023 | Failed writing received data to disk/application. | 356| 2300025 | Upload failed. | 357| 2300026 | Failed to open/read local data from file/application. | 358| 2300027 | Out of memory. | 359| 2300028 | Timeout was reached. | 360| 2300047 | Number of redirects hit maximum amount. | 361| 2300052 | Server returned nothing (no headers, no data). | 362| 2300055 | Failed sending data to the peer. | 363| 2300056 | Failure when receiving data from the peer. | 364| 2300058 | Problem with the local SSL certificate. | 365| 2300059 | Couldn't use specified SSL cipher. | 366| 2300060 | SSL peer certificate or SSH remote key was not OK. | 367| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 368| 2300063 | Maximum file size exceeded. | 369| 2300070 | Disk full or allocation exceeded. | 370| 2300073 | Remote file already exists. | 371| 2300077 | Problem with the SSL CA cert (path? access rights?). | 372| 2300078 | Remote file not found. | 373| 2300094 | An authentication function returned an error. | 374| 2300999 | Unknown Other Error. | 375 376> **错误码说明:** 377> 以上错误码的详细介绍参见[HTTP错误码](errorcode-net-http.md)。 378> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 379 380**示例:** 381 382```ts 383import http from '@ohos.net.http'; 384 385class Header { 386 public contentType: string; 387 388 constructor(contentType: string) { 389 this.contentType = contentType; 390 } 391} 392 393let httpRequest = http.createHttp(); 394let promise = httpRequest.request("EXAMPLE_URL", { 395 method: http.RequestMethod.GET, 396 connectTimeout: 60000, 397 readTimeout: 60000, 398 header: new Header('application/json') 399}); 400promise.then((data:http.HttpResponse) => { 401 console.info('Result:' + data.result); 402 console.info('code:' + data.responseCode); 403 console.info('type:' + JSON.stringify(data.resultType)); 404 console.info('header:' + JSON.stringify(data.header)); 405 console.info('cookies:' + data.cookies); // 自API version 8开始支持cookie 406 console.info('header.content-Type:' + data.header); 407 console.info('header.Status-Line:' + data.header); 408}).catch((err:Error) => { 409 console.info('error:' + JSON.stringify(err)); 410}); 411``` 412 413### destroy 414 415destroy(): void 416 417中断请求任务。 418 419**系统能力**:SystemCapability.Communication.NetStack 420 421**示例:** 422 423```ts 424import http from '@ohos.net.http'; 425let httpRequest = http.createHttp(); 426 427httpRequest.destroy(); 428``` 429 430### requestInStream<sup>10+</sup> 431 432requestInStream(url: string, callback: AsyncCallback\<number\>): void 433 434根据URL地址,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。 435 436**需要权限**:ohos.permission.INTERNET 437 438**系统能力**:SystemCapability.Communication.NetStack 439 440**参数:** 441 442| 参数名 | 类型 | 必填 | 说明 | 443| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 444| url | string | 是 | 发起网络请求的URL地址。 | 445| callback | AsyncCallback\<number\> | 是 | 回调函数。 | 446 447**错误码:** 448 449| 错误码ID | 错误信息 | 450|---------|-------------------------------------------------------| 451| 401 | Parameter error. | 452| 201 | Permission denied. | 453| 2300001 | Unsupported protocol. | 454| 2300003 | URL using bad/illegal format or missing URL. | 455| 2300005 | Couldn't resolve proxy name. | 456| 2300006 | Couldn't resolve host name. | 457| 2300007 | Couldn't connect to server. | 458| 2300008 | Weird server reply. | 459| 2300009 | Access denied to remote resource. | 460| 2300016 | Error in the HTTP2 framing layer. | 461| 2300018 | Transferred a partial file. | 462| 2300023 | Failed writing received data to disk/application. | 463| 2300025 | Upload failed. | 464| 2300026 | Failed to open/read local data from file/application. | 465| 2300027 | Out of memory. | 466| 2300028 | Timeout was reached. | 467| 2300047 | Number of redirects hit maximum amount. | 468| 2300052 | Server returned nothing (no headers, no data). | 469| 2300055 | Failed sending data to the peer. | 470| 2300056 | Failure when receiving data from the peer. | 471| 2300058 | Problem with the local SSL certificate. | 472| 2300059 | Couldn't use specified SSL cipher. | 473| 2300060 | SSL peer certificate or SSH remote key was not OK. | 474| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 475| 2300063 | Maximum file size exceeded. | 476| 2300070 | Disk full or allocation exceeded. | 477| 2300073 | Remote file already exists. | 478| 2300077 | Problem with the SSL CA cert (path? access rights?). | 479| 2300078 | Remote file not found. | 480| 2300094 | An authentication function returned an error. | 481| 2300999 | Unknown Other Error. | 482 483> **错误码说明:** 484> 以上错误码的详细介绍参见[HTTP错误码](errorcode-net-http.md)。 485> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 486 487**示例:** 488 489```ts 490import http from '@ohos.net.http'; 491import { BusinessError } from '@ohos.base'; 492 493let httpRequest = http.createHttp(); 494httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError, data: number) => { 495 if (!err) { 496 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 497 } else { 498 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 499 } 500}) 501``` 502 503### requestInStream<sup>10+</sup> 504 505requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void 506 507根据URL地址和相关配置项,发起HTTP网络请求并返回流式响应,使用callback方式作为异步方法。 508 509**需要权限**:ohos.permission.INTERNET 510 511**系统能力**:SystemCapability.Communication.NetStack 512 513**参数:** 514 515| 参数名 | 类型 | 必填 | 说明 | 516| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 517| url | string | 是 | 发起网络请求的URL地址。 | 518| options | HttpRequestOptions | 是 | 参考[HttpRequestOptions](#httprequestoptions)。 | 519| callback | AsyncCallback\<[number](#responsecode)\> | 是 | 回调函数。 | 520 521**错误码:** 522 523| 错误码ID | 错误信息 | 524|---------|-------------------------------------------------------| 525| 401 | Parameter error. | 526| 201 | Permission denied. | 527| 2300001 | Unsupported protocol. | 528| 2300003 | URL using bad/illegal format or missing URL. | 529| 2300005 | Couldn't resolve proxy name. | 530| 2300006 | Couldn't resolve host name. | 531| 2300007 | Couldn't connect to server. | 532| 2300008 | Weird server reply. | 533| 2300009 | Access denied to remote resource. | 534| 2300016 | Error in the HTTP2 framing layer. | 535| 2300018 | Transferred a partial file. | 536| 2300023 | Failed writing received data to disk/application. | 537| 2300025 | Upload failed. | 538| 2300026 | Failed to open/read local data from file/application. | 539| 2300027 | Out of memory. | 540| 2300028 | Timeout was reached. | 541| 2300047 | Number of redirects hit maximum amount. | 542| 2300052 | Server returned nothing (no headers, no data). | 543| 2300055 | Failed sending data to the peer. | 544| 2300056 | Failure when receiving data from the peer. | 545| 2300058 | Problem with the local SSL certificate. | 546| 2300059 | Couldn't use specified SSL cipher. | 547| 2300060 | SSL peer certificate or SSH remote key was not OK. | 548| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 549| 2300063 | Maximum file size exceeded. | 550| 2300070 | Disk full or allocation exceeded. | 551| 2300073 | Remote file already exists. | 552| 2300077 | Problem with the SSL CA cert (path? access rights?). | 553| 2300078 | Remote file not found. | 554| 2300094 | An authentication function returned an error. | 555| 2300999 | Unknown Other Error. | 556 557> **错误码说明:** 558> 以上错误码的详细介绍参见[HTTP错误码](errorcode-net-http.md)。 559> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 560 561**示例:** 562 563```ts 564import http from '@ohos.net.http'; 565import { BusinessError } from '@ohos.base'; 566 567let httpRequest = http.createHttp(); 568httpRequest.requestInStream("EXAMPLE_URL", (err: BusinessError<void> , data: number) => { 569 if (!err) { 570 console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data)); 571 } else { 572 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 573 } 574}) 575``` 576 577### requestInStream<sup>10+</sup> 578 579requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\> 580 581根据URL地址,发起HTTP网络请求并返回流式响应,使用Promise方式作为异步方法。 582 583**需要权限**:ohos.permission.INTERNET 584 585**系统能力**:SystemCapability.Communication.NetStack 586 587**参数:** 588 589| 参数名 | 类型 | 必填 | 说明 | 590| ------- | ------------------ | ---- | ----------------------------------------------- | 591| url | string | 是 | 发起网络请求的URL地址。 | 592| options | HttpRequestOptions | 否 | 参考[HttpRequestOptions](#httprequestoptions)。 | 593 594**返回值:** 595 596| 类型 | 说明 | 597| :------------------------------------- | :-------------------------------- | 598| Promise\<[number](#responsecode)\> | 以Promise形式返回发起请求的结果。 | 599 600**错误码:** 601 602| 错误码ID | 错误信息 | 603|---------|-------------------------------------------------------| 604| 401 | Parameter error. | 605| 201 | Permission denied. | 606| 2300001 | Unsupported protocol. | 607| 2300003 | URL using bad/illegal format or missing URL. | 608| 2300005 | Couldn't resolve proxy name. | 609| 2300006 | Couldn't resolve host name. | 610| 2300007 | Couldn't connect to server. | 611| 2300008 | Weird server reply. | 612| 2300009 | Access denied to remote resource. | 613| 2300016 | Error in the HTTP2 framing layer. | 614| 2300018 | Transferred a partial file. | 615| 2300023 | Failed writing received data to disk/application. | 616| 2300025 | Upload failed. | 617| 2300026 | Failed to open/read local data from file/application. | 618| 2300027 | Out of memory. | 619| 2300028 | Timeout was reached. | 620| 2300047 | Number of redirects hit maximum amount. | 621| 2300052 | Server returned nothing (no headers, no data). | 622| 2300055 | Failed sending data to the peer. | 623| 2300056 | Failure when receiving data from the peer. | 624| 2300058 | Problem with the local SSL certificate. | 625| 2300059 | Couldn't use specified SSL cipher. | 626| 2300060 | SSL peer certificate or SSH remote key was not OK. | 627| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.| 628| 2300063 | Maximum file size exceeded. | 629| 2300070 | Disk full or allocation exceeded. | 630| 2300073 | Remote file already exists. | 631| 2300077 | Problem with the SSL CA cert (path? access rights?). | 632| 2300078 | Remote file not found. | 633| 2300094 | An authentication function returned an error. | 634| 2300999 | Unknown Other Error. | 635 636> **错误码说明:** 637> 以上错误码的详细介绍参见[HTTP错误码](errorcode-net-http.md)。 638> HTTP 错误码映射关系:2300000 + curl错误码。更多常用错误码,可参考:[curl错误码](https://curl.se/libcurl/c/libcurl-errors.html) 639 640**示例:** 641 642```ts 643import http from '@ohos.net.http'; 644 645class Header { 646 public contentType: string; 647 648 constructor(contentType: string) { 649 this.contentType = contentType; 650 } 651} 652 653let httpRequest = http.createHttp(); 654let promise = httpRequest.requestInStream("EXAMPLE_URL", { 655 method: http.RequestMethod.GET, 656 connectTimeout: 60000, 657 readTimeout: 60000, 658 header: new Header('application/json') 659}); 660promise.then((data: number) => { 661 console.info("requestInStream OK!" + data); 662}).catch((err: Error) => { 663 console.info("requestInStream ERROR : err = " + JSON.stringify(err)); 664}); 665``` 666 667### on("headerReceive")<sup>(deprecated)</sup> 668 669on(type: "headerReceive", callback: AsyncCallback\<Object\>): void 670 671订阅HTTP Response Header 事件。 672 673> **说明:** 674> 此接口已废弃,建议使用[on("headersReceive")<sup>8+</sup>](#onheadersreceive8)替代。 675 676**系统能力**:SystemCapability.Communication.NetStack 677 678**参数:** 679 680| 参数名 | 类型 | 必填 | 说明 | 681| -------- | ----------------------- | ---- | --------------------------------- | 682| type | string | 是 | 订阅的事件类型,'headerReceive'。 | 683| callback | AsyncCallback\<Object\> | 是 | 回调函数。 | 684 685**示例:** 686 687```ts 688import http from '@ohos.net.http'; 689import { BusinessError } from '@ohos.base'; 690 691let httpRequest = http.createHttp(); 692httpRequest.on("headerReceive", (data: BusinessError) => { 693 console.info("error:" + JSON.stringify(data)); 694}); 695``` 696 697### off("headerReceive")<sup>(deprecated)</sup> 698 699off(type: "headerReceive", callback?: AsyncCallback\<Object\>): void 700 701取消订阅HTTP Response Header 事件。 702 703> **说明:** 704> 705>1. 此接口已废弃,建议使用[off("headersReceive")<sup>8+</sup>](#offheadersreceive8)替代。 706> 707>2. 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 708 709**系统能力**:SystemCapability.Communication.NetStack 710 711**参数:** 712 713| 参数名 | 类型 | 必填 | 说明 | 714| -------- | ----------------------- | ---- | ------------------------------------- | 715| type | string | 是 | 取消订阅的事件类型,'headerReceive'。 | 716| callback | AsyncCallback\<Object\> | 否 | 回调函数。 | 717 718**示例:** 719 720```ts 721import http from '@ohos.net.http'; 722 723let httpRequest = http.createHttp(); 724httpRequest.off("headerReceive"); 725``` 726 727### on("headersReceive")<sup>8+</sup> 728 729on(type: "headersReceive", callback: Callback\<Object\>): void 730 731订阅HTTP Response Header 事件。 732 733**系统能力**:SystemCapability.Communication.NetStack 734 735**参数:** 736 737| 参数名 | 类型 | 必填 | 说明 | 738| -------- | ------------------ | ---- | ---------------------------------- | 739| type | string | 是 | 订阅的事件类型:'headersReceive'。 | 740| callback | Callback\<Object\> | 是 | 回调函数。 | 741 742**示例:** 743 744```ts 745import http from '@ohos.net.http'; 746 747let httpRequest = http.createHttp(); 748httpRequest.on("headersReceive", (header: Object) => { 749 console.info("header: " + JSON.stringify(header)); 750}); 751httpRequest.off("headersReceive"); 752``` 753 754### off("headersReceive")<sup>8+</sup> 755 756off(type: "headersReceive", callback?: Callback\<Object\>): void 757 758取消订阅HTTP Response Header 事件。 759 760> **说明:** 761> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 762 763**系统能力**:SystemCapability.Communication.NetStack 764 765**参数:** 766 767| 参数名 | 类型 | 必填 | 说明 | 768| -------- | ------------------ | ---- | -------------------------------------- | 769| type | string | 是 | 取消订阅的事件类型:'headersReceive'。 | 770| callback | Callback\<Object\> | 否 | 回调函数。 | 771 772**示例:** 773 774```ts 775import http from '@ohos.net.http'; 776 777let httpRequest = http.createHttp(); 778httpRequest.on("headersReceive", (header: Object) => { 779 console.info("header: " + JSON.stringify(header)); 780}); 781httpRequest.off("headersReceive"); 782``` 783 784### once("headersReceive")<sup>8+</sup> 785 786once(type: "headersReceive", callback: Callback\<Object\>): void 787 788订阅HTTP Response Header 事件,但是只触发一次。一旦触发之后,订阅器就会被移除。使用callback方式作为异步方法。 789 790**系统能力**:SystemCapability.Communication.NetStack 791 792**参数:** 793 794| 参数名 | 类型 | 必填 | 说明 | 795| -------- | ------------------ | ---- | ---------------------------------- | 796| type | string | 是 | 订阅的事件类型:'headersReceive'。 | 797| callback | Callback\<Object\> | 是 | 回调函数。 | 798 799**示例:** 800 801```ts 802import http from '@ohos.net.http'; 803 804let httpRequest = http.createHttp(); 805httpRequest.once("headersReceive", (header: Object) => { 806 console.info("header: " + JSON.stringify(header)); 807}); 808``` 809 810### on("dataReceive")<sup>10+</sup> 811 812on(type: "dataReceive", callback: Callback\<ArrayBuffer\>): void 813 814订阅HTTP流式响应数据接收事件。 815 816> **说明:** 817> 暂不支持订阅HTTP流式数据上传的相关事件。 818 819**系统能力**:SystemCapability.Communication.NetStack 820 821**参数:** 822 823| 参数名 | 类型 | 必填 | 说明 | 824| -------- | ----------------------- | ---- | --------------------------------- | 825| type | string | 是 | 订阅的事件类型,'dataReceive'。 | 826| callback | AsyncCallback\<ArrayBuffer\> | 是 | 回调函数。 | 827 828**示例:** 829 830```ts 831import http from '@ohos.net.http'; 832 833let httpRequest = http.createHttp(); 834httpRequest.on("dataReceive", (data: ArrayBuffer) => { 835 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 836}); 837httpRequest.off("dataReceive"); 838``` 839 840### off("dataReceive")<sup>10+</sup> 841 842off(type: "dataReceive", callback?: Callback\<ArrayBuffer\>): void 843 844取消订阅HTTP流式响应数据接收事件。 845 846> **说明:** 847> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 848 849**系统能力**:SystemCapability.Communication.NetStack 850 851**参数:** 852 853| 参数名 | 类型 | 必填 | 说明 | 854| -------- | ------------------ | ---- | -------------------------------------- | 855| type | string | 是 | 取消订阅的事件类型:'dataReceive'。 | 856| callback | Callback\<ArrayBuffer\> | 否 | 回调函数。 | 857 858**示例:** 859 860```ts 861import http from '@ohos.net.http'; 862 863let httpRequest = http.createHttp(); 864httpRequest.on("dataReceive", (data: ArrayBuffer) => { 865 console.info("dataReceive length: " + JSON.stringify(data.byteLength)); 866}); 867httpRequest.off("dataReceive"); 868``` 869 870### on("dataEnd")<sup>10+</sup> 871 872on(type: "dataEnd", callback: Callback\<void\>): void 873 874订阅HTTP流式响应数据接收完毕事件。 875 876> **说明:** 877> 暂不支持订阅HTTP流式数据上传的相关事件。 878 879**系统能力**:SystemCapability.Communication.NetStack 880 881**参数:** 882 883| 参数名 | 类型 | 必填 | 说明 | 884| -------- | ----------------------- | ---- | --------------------------------- | 885| type | string | 是 | 订阅的事件类型,'dataEnd'。 | 886| callback | AsyncCallback\<void\> | 是 | 回调函数。 | 887 888**示例:** 889 890```ts 891import http from '@ohos.net.http'; 892 893let httpRequest = http.createHttp(); 894httpRequest.on("dataEnd", () => { 895 console.info("Receive dataEnd !"); 896}); 897httpRequest.off("dataEnd"); 898``` 899 900### off("dataEnd")<sup>10+</sup> 901 902off(type: "dataEnd", callback?: Callback\<void\>): void 903 904取消订阅HTTP流式响应数据接收完毕事件。 905 906> **说明:** 907> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 908 909**系统能力**:SystemCapability.Communication.NetStack 910 911**参数:** 912 913| 参数名 | 类型 | 必填 | 说明 | 914| -------- | ------------------ | ---- | -------------------------------------- | 915| type | string | 是 | 取消订阅的事件类型:'dataEnd'。 | 916| callback | Callback\<void\> | 否 | 回调函数。 | 917 918**示例:** 919 920```ts 921import http from '@ohos.net.http'; 922 923let httpRequest = http.createHttp(); 924httpRequest.on("dataEnd", () => { 925 console.info("Receive dataEnd !"); 926}); 927httpRequest.off("dataEnd"); 928``` 929 930### on("dataReceiveProgress")<sup>10+</sup> 931 932on(type: "dataReceiveProgress", callback: Callback\<DataReceiveProgressInfo\>): void 933 934订阅HTTP流式响应数据接收进度事件。 935 936> **说明:** 937> 暂不支持订阅HTTP流式数据上传的相关事件。 938 939**系统能力**:SystemCapability.Communication.NetStack 940 941**参数:** 942 943| 参数名 | 类型 | 必填 | 说明 | 944| -------- | ----------------------- | ---- | --------------------------------- | 945| type | string | 是 | 订阅的事件类型,'dataReceiveProgress'。 | 946| callback | AsyncCallback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | 是 | 回调函数。返回数据接收进度信息。 | 947 948**示例:** 949 950```ts 951import http from '@ohos.net.http'; 952 953class RequestData { 954 receiveSize: number = 2000 955 totalSize: number = 2000 956} 957 958let httpRequest = http.createHttp(); 959httpRequest.on("dataReceiveProgress", (data: RequestData) => { 960 console.info("dataReceiveProgress:" + JSON.stringify(data)); 961}); 962httpRequest.off("dataReceiveProgress"); 963``` 964 965### off("dataReceiveProgress")<sup>10+</sup> 966 967off(type: "dataReceiveProgress", callback?: Callback\<DataReceiveProgressInfo\>): void 968 969取消订阅HTTP流式响应数据接收进度事件。 970 971> **说明:** 972> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 973 974**系统能力**:SystemCapability.Communication.NetStack 975 976**参数:** 977 978| 参数名 | 类型 | 必填 | 说明 | 979| -------- | ------------------ | ---- | -------------------------------------- | 980| type | string | 是 | 取消订阅的事件类型:'dataReceiveProgress'。 | 981| callback | Callback\<[DataReceiveProgressInfo](#datareceiveprogressinfo11)\> | 否 | 回调函数。 返回数据接收进度信息。 | 982 983**示例:** 984 985```ts 986import http from '@ohos.net.http'; 987 988class RequestData { 989 receiveSize: number = 2000 990 totalSize: number = 2000 991} 992 993let httpRequest = http.createHttp(); 994httpRequest.on("dataReceiveProgress", (data: RequestData) => { 995 console.info("dataReceiveProgress:" + JSON.stringify(data)); 996}); 997httpRequest.off("dataReceiveProgress"); 998``` 999 1000### on("dataSendProgress")<sup>11+</sup> 1001 1002on(type: "dataSendProgress", callback: Callback\<DataSendProgressInfo\>): void 1003 1004订阅HTTP网络请求数据发送进度事件。 1005 1006**系统能力**:SystemCapability.Communication.NetStack 1007 1008**参数:** 1009 1010| 参数名 | 类型 | 必填 | 说明 | 1011| -------- | ----------------------- | ---- | --------------------------------- | 1012| type | string | 是 | 订阅的事件类型,'dataSendProgress'。 | 1013| callback | AsyncCallback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | 是 | 回调函数。返回数据发送进度信息。| 1014 1015**示例:** 1016 1017```ts 1018import http from '@ohos.net.http'; 1019 1020class SendData { 1021 sendSize: number = 2000 1022 totalSize: number = 2000 1023} 1024 1025let httpRequest = http.createHttp(); 1026httpRequest.on("dataSendProgress", (data: SendData) => { 1027 console.info("dataSendProgress:" + JSON.stringify(data)); 1028}); 1029httpRequest.off("dataSendProgress"); 1030``` 1031 1032### off("dataSendProgress")<sup>11+</sup> 1033 1034off(type: "dataSendProgress", callback?: Callback\<DataSendProgressInfo\>): void 1035 1036取消订阅HTTP网络请求数据发送进度事件。 1037 1038> **说明:** 1039> 可以指定传入on中的callback取消一个订阅,也可以不指定callback清空所有订阅。 1040 1041**系统能力**:SystemCapability.Communication.NetStack 1042 1043**参数:** 1044 1045| 参数名 | 类型 | 必填 | 说明 | 1046| -------- | ------------------ | ---- | -------------------------------------- | 1047| type | string | 是 | 取消订阅的事件类型:'dataSendProgress'。 | 1048| callback | Callback\<[DataSendProgressInfo](#datasendprogressinfo11)\> | 否 | 回调函数。返回数据接发送进度信息。 | 1049 1050**示例:** 1051 1052```ts 1053import http from '@ohos.net.http'; 1054 1055class SendData { 1056 sendSize: number = 2000 1057 totalSize: number = 2000 1058} 1059 1060let httpRequest = http.createHttp(); 1061httpRequest.on("dataSendProgress", (data: SendData) => { 1062 console.info("dataSendProgress:" + JSON.stringify(data)); 1063}); 1064httpRequest.off("dataSendProgress"); 1065``` 1066 1067## HttpRequestOptions 1068 1069发起请求可选参数的类型和取值范围。 1070 1071**系统能力**:SystemCapability.Communication.NetStack 1072 1073| 名称 | 类型 | 必填 | 说明 | 1074| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | 1075| method | [RequestMethod](#requestmethod) | 否 | 请求方式,默认为GET。 | 1076| extraData | string \| Object \| ArrayBuffer | 否 | 发送请求的额外数据,默认无此字段。<br />当HTTP请求为POST、PUT等方法时,此字段为HTTP请求的content,以UTF-8编码形式作为请求体。当'content-Type'为'application/x-www-form-urlencoded'时,请求提交的信息主体数据应在key和value进行URL转码后按照键值对"key1=value1&key2=value2&key3=value3"的方式进行编码,该字段对应的类型通常为String;当'content-Type'为'text/xml'时,该字段对应的类型通常为String;当'content-Type'为'application/json'时,该字段对应的类型通常为Object;当'content-Type'为'application/octet-stream'时,该字段对应的类型通常为ArrayBuffer;当'content-Type'为'multipart/form-data'且需上传的字段为文件时,该字段对应的类型通常为ArrayBuffer。以上信息仅供参考,并可能根据具体情况有所不同。<br />- 当HTTP请求为GET、OPTIONS、DELETE、TRACE、CONNECT等方法时,此字段为HTTP请求参数的补充。开发者需传入Encode编码后的string类型参数,Object类型的参数无需预编码,参数内容会拼接到URL中进行发送;ArrayBuffer类型的参数不会做拼接处理。 | 1077| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 否 | 指定返回数据的类型,默认无此字段。如果设置了此参数,系统将优先返回指定的类型。 | 1078| usingCache<sup>9+</sup> | boolean | 否 | 是否使用缓存,默认为true,请求时优先读取缓存。 缓存跟随当前进程生效。新缓存会替换旧缓存。 | 1079| priority<sup>9+</sup> | number | 否 | 优先级,范围[1,1000],默认是1。 | 1080| header | Object | 否 | HTTP请求头字段。默认{'content-Type': 'application/json'}。 | 1081| readTimeout | number | 否 | 读取超时时间。单位为毫秒(ms),默认为60000ms。<br />设置为0表示不会出现超时情况。 | 1082| connectTimeout | number | 否 | 连接超时时间。单位为毫秒(ms),默认为60000ms。 | 1083| usingProtocol<sup>9+</sup> | [HttpProtocol](#httpprotocol9) | 否 | 使用协议。默认值由系统自动指定。 | 1084| usingProxy<sup>10+</sup> | boolean \| HttpProxy | 否 | 是否使用HTTP代理,默认为false,不使用代理。<br />- 当usingProxy为布尔类型true时,使用默认网络代理。<br />- 当usingProxy为HttpProxy类型时,使用指定网络代理。 | 1085| caPath<sup>10+</sup> | string | 否 | 如果设置了此参数,系统将使用用户指定路径的CA证书,(开发者需保证该路径下CA证书的可访问性),否则将使用系统预设CA证书,系统预设CA证书位置:/etc/ssl/certs/cacert.pem。证书路径为沙箱映射路径(开发者可通过Global.getContext().filesDir获取应用沙箱路径)。目前仅支持后缀名为.pem的文本格式证书。 | 1086| resumeFrom<sup>11+</sup> | number | 否 | 用于设置上传或下载起始位置。HTTP标准(RFC 7233第3.1节)允许服务器忽略范围请求。<br />-使用HTTP PUT时设置此参数,可能出现未知问题。<br />-取值范围是:1~4294967296(4GB),超出范围则不生效。 | 1087| resumeTo<sup>11+</sup> | number | 否 | 用于设置上传或下载结束位置。HTTP标准(RFC 7233第3.1节)允许服务器忽略范围请求。<br />-使用HTTP PUT时设置此参数,可能出现未知问题。<br />-取值范围是:1~4294967296(4GB),超出范围则不生效。 | 1088| clientCert<sup>11+</sup> | [ClientCert](#clientcert11) | 否 | 支持传输客户端证书 | 1089| dnsOverHttps<sup>11+</sup> | string | 否 | 设置使用https协议的服务器进行DNS解析。<br />-参数必须以以下格式进行URL编码:"https:// host:port/path"。 | 1090| dnsServers<sup>11+</sup> | Array<string> | 否 | 设置指定的DNS服务器进行DNS解析。<br />-可以设置多个DNS解析服务器,最多3个服务器。如果有3个以上,只取前3个。<br />-服务器必须是IPV4或者IPV6地址。 | 1091| maxLimit<sup>11+</sup> | number | 否 | 响应消息的最大字节限制,默认值为5*1024*1024,以字节为单位。最大值为100*1024*1024,以字节为单位。 | 1092| multiFormDataList<sup>11+</sup> | Array<[MultiFormData](#multiformdata11)> | 否 | 当'content-Type'为'multipart/form-data'时,则上传该字段定义的数据字段表单列表。 | 1093 1094## RequestMethod 1095 1096HTTP 请求方法。 1097 1098**系统能力**:SystemCapability.Communication.NetStack 1099 1100| 名称 | 值 | 说明 | 1101| :------ | ------- | :------------------ | 1102| OPTIONS | "OPTIONS" | HTTP 请求 OPTIONS。 | 1103| GET | "GET" | HTTP 请求 GET。 | 1104| HEAD | "HEAD" | HTTP 请求 HEAD。 | 1105| POST | "POST" | HTTP 请求 POST。 | 1106| PUT | "PUT" | HTTP 请求 PUT。 | 1107| DELETE | "DELETE" | HTTP 请求 DELETE。 | 1108| TRACE | "TRACE" | HTTP 请求 TRACE。 | 1109| CONNECT | "CONNECT" | HTTP 请求 CONNECT。 | 1110 1111## ResponseCode 1112 1113发起请求返回的响应码。 1114 1115**系统能力**:SystemCapability.Communication.NetStack 1116 1117| 名称 | 值 | 说明 | 1118| ----------------- | ---- | ------------------------------------------------------------ | 1119| OK | 200 | 请求成功。一般用于GET与POST请求。 | 1120| CREATED | 201 | 已创建。成功请求并创建了新的资源。 | 1121| ACCEPTED | 202 | 已接受。已经接受请求,但未处理完成。 | 1122| NOT_AUTHORITATIVE | 203 | 非授权信息。请求成功。 | 1123| NO_CONTENT | 204 | 无内容。服务器成功处理,但未返回内容。 | 1124| RESET | 205 | 重置内容。 | 1125| PARTIAL | 206 | 部分内容。服务器成功处理了部分GET请求。 | 1126| MULT_CHOICE | 300 | 多种选择。 | 1127| MOVED_PERM | 301 | 永久移动。请求的资源已被永久的移动到新URI,返回信息会包括新的URI,浏览器会自动定向到新URI。 | 1128| MOVED_TEMP | 302 | 临时移动。 | 1129| SEE_OTHER | 303 | 查看其它地址。 | 1130| NOT_MODIFIED | 304 | 未修改。 | 1131| USE_PROXY | 305 | 使用代理。 | 1132| BAD_REQUEST | 400 | 客户端请求的语法错误,服务器无法理解。 | 1133| UNAUTHORIZED | 401 | 请求要求用户的身份认证。 | 1134| PAYMENT_REQUIRED | 402 | 保留,将来使用。 | 1135| FORBIDDEN | 403 | 服务器理解请求客户端的请求,但是拒绝执行此请求。 | 1136| NOT_FOUND | 404 | 服务器无法根据客户端的请求找到资源(网页)。 | 1137| BAD_METHOD | 405 | 客户端请求中的方法被禁止。 | 1138| NOT_ACCEPTABLE | 406 | 服务器无法根据客户端请求的内容特性完成请求。 | 1139| PROXY_AUTH | 407 | 请求要求代理的身份认证。 | 1140| CLIENT_TIMEOUT | 408 | 请求时间过长,超时。 | 1141| CONFLICT | 409 | 服务器完成客户端的PUT请求是可能返回此代码,服务器处理请求时发生了冲突。 | 1142| GONE | 410 | 客户端请求的资源已经不存在。 | 1143| LENGTH_REQUIRED | 411 | 服务器无法处理客户端发送的不带Content-Length的请求信息。 | 1144| PRECON_FAILED | 412 | 客户端请求信息的先决条件错误。 | 1145| ENTITY_TOO_LARGE | 413 | 由于请求的实体过大,服务器无法处理,因此拒绝请求。 | 1146| REQ_TOO_LONG | 414 | 请求的URI过长(URI通常为网址),服务器无法处理。 | 1147| UNSUPPORTED_TYPE | 415 | 服务器无法处理请求的格式。 | 1148| RANGE_NOT_SATISFIABLE | 416 | 请求范围不符合要求。 | 1149| INTERNAL_ERROR | 500 | 服务器内部错误,无法完成请求。 | 1150| NOT_IMPLEMENTED | 501 | 服务器不支持请求的功能,无法完成请求。 | 1151| BAD_GATEWAY | 502 | 充当网关或代理的服务器,从远端服务器接收到了一个无效的请求。 | 1152| UNAVAILABLE | 503 | 由于超载或系统维护,服务器暂时的无法处理客户端的请求。 | 1153| GATEWAY_TIMEOUT | 504 | 充当网关或代理的服务器,未及时从远端服务器获取请求。 | 1154| VERSION | 505 | 服务器请求的HTTP协议的版本。 | 1155 1156## HttpResponse 1157 1158request方法回调函数的返回值类型。 1159 1160**系统能力**:SystemCapability.Communication.NetStack 1161 1162| 名称 | 类型 | 必填 | 说明 | 1163| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 1164| result | string \| Object<sup>deprecated 8+</sup> \| ArrayBuffer<sup>8+</sup> | 是 | HTTP请求根据响应头中content-type类型返回对应的响应格式内容,若HttpRequestOptions无expectDataType字段,按如下规则返回:<br />- application/json:返回JSON格式的字符串;<br />- application/octet-stream:ArrayBuffer;<br />- image:ArrayBuffer;<br />- 其他:string。<br /> 若HttpRequestOption有expectDataType字段,开发者需传入与服务器返回类型相同的数据类型。 | 1165| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | 是 | 返回值类型。 | 1166| responseCode | [ResponseCode](#responsecode) \| number | 是 | 回调函数执行成功时,此字段为[ResponseCode](#responsecode)。若执行失败,错误码将会从AsyncCallback中的err字段返回。 | 1167| 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']; | 1168| cookies<sup>8+</sup> | string | 是 | 服务器返回的 cookies。 | 1169| performanceTiming<sup>11+</sup> | [PerformanceTiming](#performancetiming11) | 是 | HTTP请求的各个阶段的耗时。| 1170 1171## ClientCert<sup>11+</sup> 1172 1173客户端证书类型。 1174 1175**系统能力**:SystemCapability.Communication.NetStack 1176 1177| 名称 | 类型 | 必填 | 说明 | 1178| -------- | -------| --- | ----------- | 1179| certPath | string | 是 | 证书路径 | 1180| certType | [CertType](#certtype11) | 否 | 证书类型,默认是PEM | 1181| keyPath | string | 是 | 证书秘钥的路径 | 1182| keyPassword | string | 否 | 证书秘钥的密码 | 1183 1184## PerformanceTiming<sup>11+</sup> 1185 1186性能打点(单位:毫秒)。 1187 1188**系统能力**:SystemCapability.Communication.NetStack 1189 1190| 名称 | 类型 | 必填 | 说明 | 1191| ---------- | ------ | ---- | --------------------- | 1192| dnsTiming | number | 是 | 从[request](#request)请求到DNS解析完成耗时。 | 1193| tcpTiming | number | 是 | 从[request](#request)请求到TCP连接完成耗时。 | 1194| tlsTiming | number | 是 | 从[request](#request)请求到TLS连接完成耗时。 | 1195| firstSendTiming | number | 是 | 从[request](#request)请求到开始发送第一个字节的耗时。 | 1196| firstReceiveTiming | number | 是 | 从[request](#request)请求到接收第一个字节的耗时。 | 1197| totalFinishTiming | number | 是 | 从[request](#request)请求到完成请求的耗时。 | 1198| redirectTiming | number | 是 | 从[request](#request)请求到完成所有重定向步骤的耗时。 | 1199| responseHeaderTiming | number | 是 | 从[request](#request)请求到header解析完成的耗时。 | 1200| responseBodyTiming | number | 是 | 从[request](#request)请求到body解析完成的耗时。 | 1201| totalTiming | number | 是 | 从[request](#request)请求回调到应用程序的耗时。 | 1202 1203## DataReceiveProgressInfo<sup>11+</sup> 1204 1205数据接收信息 1206 1207**系统能力**:SystemCapability.Communication.NetStack 1208 1209| 名称 | 类型 | 必填 | 说明 | 1210| ---- | ---- | ---- | ---- | 1211| receiveSize | number | 是 | 已接收的数据量(字节)。 | 1212| totalSize| number | 是 | 总共要接收的数据量(字节)| 1213 1214## DataSendProgressInfo<sup>11+</sup> 1215 1216数据发送信息 1217 1218**系统能力**:SystemCapability.Communication.NetStack 1219 1220### 属性 1221 1222| 名称 | 类型 | 必填 | 说明 | 1223| ---- | ---- | ---- | ---- | 1224| sendSize | number | 是 | 每次发送的数据量(字节)。 | 1225| totalSize | number | 是 | 总共要发送的数据量(字节)。 | 1226 1227## MultiFormData<sup>11+</sup> 1228 1229多部分表单数据的类型。 1230 1231**系统能力**:SystemCapability.Communication.NetStack 1232 1233| 名称 | 类型 | 必填 | 说明 | 1234| ---- | ---- | ---- | ---- | 1235| name | string | 是 | 数据名称 | 1236| contentType | string | 是 | 数据类型,如'text/plain','image/png', 'image/jpeg', 'audio/mpeg', 'video/mp4'等 | 1237| remoteFileName | string | 否 | 上传到服务器保存为文件的名称。 | 1238| data | string \| Object \| ArrayBuffer | 否 | 表单数据内容。 | 1239| filePath | string | 否 | 此参数根据文件的内容设置mime部件的正文内容。用于代替data将文件数据设置为数据内容,如果data为空,则必须设置filePath。如果data有值,则filePath不会生效。| 1240 1241## http.createHttpResponseCache<sup>9+</sup> 1242 1243createHttpResponseCache(cacheSize?: number): HttpResponseCache 1244 1245创建一个HttpResponseCache对象,可用于存储HTTP请求的响应数据。对象中可调用flush与delete方法,cacheSize指定缓存大小。 1246 1247**系统能力**:SystemCapability.Communication.NetStack 1248 1249**参数:** 1250 1251| 参数名 | 类型 | 必填 | 说明 | 1252| -------- | --------------------------------------- | ---- | ---------- | 1253| cacheSize | number | 否 | 缓存大小最大为10\*1024\*1024(10MB),默认最大。 | 1254 1255**返回值:** 1256 1257| 类型 | 说明 | 1258| :---------- | :----------------------------------------------------------- | 1259| [HttpResponseCache](#httpresponsecache9) | 返回一个存储HTTP访问请求响应的对象。 | 1260 1261**示例:** 1262 1263```ts 1264import http from '@ohos.net.http'; 1265 1266let httpResponseCache = http.createHttpResponseCache(); 1267``` 1268 1269## HttpResponseCache<sup>9+</sup> 1270 1271存储HTTP访问请求响应的对象。在调用HttpResponseCache的方法前,需要先通过[createHttpResponseCache()](#httpcreatehttpresponsecache9)创建一个任务。 1272 1273### flush<sup>9+</sup> 1274 1275flush(callback: AsyncCallback\<void\>): void 1276 1277将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用callback方式作为异步方法。缓存数据包括:响应头(header)、响应体(result)、cookies、请求时间(requestTime)和响应时间(responseTime)。 1278 1279**系统能力**:SystemCapability.Communication.NetStack 1280 1281**参数:** 1282 1283| 参数名 | 类型 | 必填 | 说明 | 1284| -------- | --------------------------------------- | ---- | ---------- | 1285| callback | AsyncCallback\<void\> | 是 | 回调函数返回写入结果。 | 1286 1287**示例:** 1288 1289```ts 1290import http from '@ohos.net.http'; 1291import { BusinessError } from '@ohos.base'; 1292 1293let httpResponseCache = http.createHttpResponseCache(); 1294let httpRequest = http.createHttp(); 1295httpRequest.request("EXAMPLE_URL", (err: BusinessError, data: http.HttpResponse) => { 1296 if (!err) { 1297 httpResponseCache.flush((err: BusinessError) => { 1298 if (err) { 1299 console.error('flush fail'); 1300 } 1301 console.info('flush success'); 1302 }); 1303 httpRequest.destroy(); 1304 } else { 1305 console.error('error:' + JSON.stringify(err)); 1306 // 当该请求使用完毕时,开发者务必调用destroy方法主动销毁该JavaScript Object。 1307 httpRequest.destroy(); 1308 } 1309}); 1310``` 1311 1312### flush<sup>9+</sup> 1313 1314flush(): Promise\<void\> 1315 1316将缓存中的数据写入文件系统,以便在下一个HTTP请求中访问所有缓存数据,使用Promise方式作为异步方法。 1317 1318**系统能力**:SystemCapability.Communication.NetStack 1319 1320**返回值:** 1321 1322| 类型 | 说明 | 1323| --------------------------------- | ------------------------------------- | 1324| Promise\<void\> | 以Promise形式返回写入结果。 | 1325 1326**示例:** 1327 1328```ts 1329import http from '@ohos.net.http'; 1330import { BusinessError } from '@ohos.base'; 1331 1332let httpRequest = http.createHttp(); 1333let httpResponseCache = http.createHttpResponseCache(); 1334let promise = httpRequest.request("EXAMPLE_URL"); 1335 1336promise.then((data: http.HttpResponse) => { 1337 httpResponseCache.flush().then(() => { 1338 console.error('flush success'); 1339 }).catch((err: BusinessError) => { 1340 console.info('flush fail'); 1341 }); 1342}).catch((err: Error) => { 1343 console.error('error:' + JSON.stringify(err)); 1344}); 1345``` 1346 1347### delete<sup>9+</sup> 1348 1349delete(callback: AsyncCallback\<void\>): void 1350 1351禁用缓存并删除其中的数据,使用callback方式作为异步方法。 1352 1353**系统能力**:SystemCapability.Communication.NetStack 1354 1355**参数:** 1356 1357| 参数名 | 类型 | 必填 | 说明 | 1358| -------- | --------------------------------------- | ---- | ---------- | 1359| callback | AsyncCallback\<void\> | 是 | 回调函数返回删除结果。| 1360 1361**示例:** 1362 1363```ts 1364import http from '@ohos.net.http'; 1365import { BusinessError } from '@ohos.base'; 1366 1367let httpRequest = http.createHttp(); 1368httpRequest.request("EXAMPLE_URL").then(data => { 1369 const httpResponseCache = http.createHttpResponseCache(); 1370 httpResponseCache.delete((err: BusinessError) => { 1371 try { 1372 if (err) { 1373 console.error('fail: ' + err); 1374 } else { 1375 console.info('success'); 1376 } 1377 } catch (err) { 1378 console.error('error: ' + err); 1379 } 1380 }); 1381 httpRequest.destroy(); 1382}).catch(error => { 1383 console.error("errocode" + JSON.stringify(error)); 1384}); 1385``` 1386 1387### delete<sup>9+</sup> 1388 1389delete(): Promise\<void\> 1390 1391禁用缓存并删除其中的数据,使用Promise方式作为异步方法。 1392 1393**系统能力**:SystemCapability.Communication.NetStack 1394 1395**返回值:** 1396 1397| 类型 | 说明 | 1398| --------------------------------- | ------------------------------------- | 1399| Promise\<void\> | 以Promise形式返回删除结果。 | 1400 1401**示例:** 1402 1403```ts 1404import http from '@ohos.net.http'; 1405import { BusinessError } from '@ohos.base'; 1406 1407let httpRequest = http.createHttp(); 1408httpRequest.request("EXAMPLE_URL").then(data => { 1409 const httpResponseCache = http.createHttpResponseCache(); 1410 httpResponseCache.delete().then(() => { 1411 console.log("success"); 1412 }).catch((err: BusinessError) => { 1413 console.error("fail"); 1414 }); 1415 httpRequest.destroy(); 1416}).catch((error: BusinessError) => { 1417 console.error("errocode" + JSON.stringify(error)); 1418}); 1419``` 1420 1421## HttpDataType<sup>9+</sup> 1422 1423http的数据类型。 1424 1425**系统能力**:SystemCapability.Communication.NetStack 1426 1427| 名称 | 值 | 说明 | 1428| ------------------ | -- | ----------- | 1429| STRING | 0 | 字符串类型。 | 1430| OBJECT | 1 | 对象类型。 | 1431| ARRAY_BUFFER | 2 | 二进制数组类型。| 1432 1433## HttpProtocol<sup>9+</sup> 1434 1435http协议版本。 1436 1437**系统能力**:SystemCapability.Communication.NetStack 1438 1439| 名称 | 说明 | 1440| :-------- | :----------- | 1441| HTTP1_1 | 协议http1.1 | 1442| HTTP2 | 协议http2 | 1443| HTTP3<sup>11+</sup> | 协议http3,若系统或服务器不支持,则使用低版本的http协议请求。<br />-仅对https的URL生效,http则会请求失败。 | 1444 1445## CertType<sup>11+</sup> 1446 1447证书类型的枚举。 1448 1449**系统能力**:SystemCapability.Communication.NetStack 1450 1451| 名称 | 说明 | 1452| --- | ---------- | 1453| PEM | 证书类型PEM | 1454| DER | 证书类型DER | 1455| P12 | 证书类型P12 |