1# Data Request 2 3> **NOTE**<br> 4> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. 5 6## Modules to Import 7 8``` 9import http from '@ohos.net.http'; 10``` 11 12## Example 13 14``` 15import http from '@ohos.net.http'; 16 17// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. 18let httpRequest = http.createHttp(); 19// Subscribe to the HTTP response header, which is returned earlier than HttpRequest. You can subscribe to HTTP Response Header events based on service requirements. 20// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+ 21httpRequest.on('headersReceive', (header) => { 22 console.info('header: ' + JSON.stringify(header)); 23}); 24httpRequest.request( 25 // Set the URL of the HTTP request. You need to define the URL. Set the parameters of the request in extraData. 26 "EXAMPLE_URL", 27 { 28 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 29 // You can add the header field based on service requirements. 30 header: { 31 'Content-Type': 'application/json' 32 }, 33 // This field is used to transfer data when the POST request is used. 34 extraData: { 35 "data": "data to send", 36 }, 37 connectTimeout: 60000, // Optional. The default value is 60000, in ms. 38 readTimeout: 60000, // Optional. The default value is 60000, in ms. 39 }, (err, data) => { 40 if (!err) { 41 // data.result contains the HTTP response. Parse the response based on service requirements. 42 console.info('Result:' + data.result); 43 console.info('code:' + data.responseCode); 44 // data.header contains the HTTP response header. Parse the content based on service requirements. 45 console.info('header:' + JSON.stringify(data.header)); 46 console.info('cookies:' + data.cookies); // 8+ 47 } else { 48 console.info('error:' + JSON.stringify(err)); 49 // Call the destroy() method to release resources after the call is complete. 50 httpRequest.destroy(); 51 } 52 } 53); 54``` 55 56## http.createHttp 57 58createHttp\(\): HttpRequest 59 60Creates an HTTP request. You can use this API to initiate or destroy an HTTP request, or enable or disable listening for HTTP Response Header events. An HttpRequest object corresponds to an HTTP request. To initiate multiple HTTP requests, you must create an **HttpRequest** object for each HTTP request. 61 62**System capability**: SystemCapability.Communication.NetStack 63 64**Return value** 65 66| Type | Description | 67| :---------- | :----------------------------------------------------------- | 68| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.| 69 70**Example** 71 72``` 73import http from '@ohos.net.http'; 74let httpRequest = http.createHttp(); 75``` 76 77 78## HttpRequest 79 80Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. 81 82### request 83 84request\(url: string, callback: AsyncCallback\<HttpResponse\>\):void 85 86Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. 87 88**Required permission**: ohos.permission.INTERNET 89 90**System capability**: SystemCapability.Communication.NetStack 91 92**Parameters** 93 94| Name | Type | Mandatory| Description | 95| -------- | ------------------------------------------------------- | ---- | ----------------------- | 96| url | string | Yes | URL for initiating an HTTP request.| 97| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | 98 99**Example** 100 101``` 102httpRequest.request("EXAMPLE_URL", (err, data) => { 103 if (!err) { 104 console.info('Result:' + data.result); 105 console.info('code:' + data.responseCode); 106 console.info('header:' + JSON.stringify(data.header)); 107 console.info('cookies:' + data.cookies); // 8+ 108 } else { 109 console.info('error:' + JSON.stringify(err)); 110 } 111}); 112``` 113 114### request 115 116request\(url: string, options: HttpRequestOptions, callback: AsyncCallback<HttpResponse\>\):void 117 118Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result. 119 120**Required permission**: ohos.permission.INTERNET 121 122**System capability**: SystemCapability.Communication.NetStack 123 124**Parameters** 125 126| Name | Type | Mandatory| Description | 127| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | 128| url | string | Yes | URL for initiating an HTTP request. | 129| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 130| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. | 131 132**Example** 133 134``` 135httpRequest.request("EXAMPLE_URL", 136{ 137 method: http.RequestMethod.GET, 138 header: { 139 'Content-Type': 'application/json' 140 }, 141 readTimeout: 60000, 142 connectTimeout: 60000 143}, (err, data) => { 144 if (!err) { 145 console.info('Result:' + data.result); 146 console.info('code:' + data.responseCode); 147 console.info('header:' + JSON.stringify(data.header)); 148 console.info('cookies:' + data.cookies); // 8+ 149 console.info('header.Content-Type:' + data.header['Content-Type']); 150 console.info('header.Status-Line:' + data.header['Status-Line']); 151 } else { 152 console.info('error:' + JSON.stringify(err)); 153 } 154}); 155``` 156 157 158### request 159 160request\(url: string, options? : HttpRequestOptions\): Promise<HttpResponse\> 161 162Initiates an HTTP request to a given URL. This API uses a promise to return the result. 163 164**Required permission**: ohos.permission.INTERNET 165 166**System capability**: SystemCapability.Communication.NetStack 167 168**Parameters** 169 170| Name | Type | Mandatory| Description | 171| ------- | ------------------ | ---- | -------------------------------------------------- | 172| url | string | Yes | URL for initiating an HTTP request. | 173| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| 174 175**Return value** 176 177| Type | Description | 178| :-------------------- | :-------------------------------- | 179| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| 180 181 182**Example** 183 184``` 185let promise = httpRequest.request("EXAMPLE_URL", { 186 method: http.RequestMethod.GET, 187 connectTimeout: 60000, 188 readTimeout: 60000, 189 header: { 190 'Content-Type': 'application/json' 191 } 192}); 193promise.then((data) => { 194 console.info('Result:' + data.result); 195 console.info('code:' + data.responseCode); 196 console.info('header:' + JSON.stringify(data.header)); 197 console.info('cookies:' + data.cookies); // 8+ 198 console.info('header.Content-Type:' + data.header['Content-Type']); 199 console.info('header.Status-Line:' + data.header['Status-Line']); 200}).catch((err) => { 201 console.info('error:' + JSON.stringify(err)); 202}); 203``` 204 205### destroy 206 207destroy\(\): void 208 209Destroys an HTTP request. 210 211**System capability**: SystemCapability.Communication.NetStack 212 213**Example** 214 215``` 216httpRequest.destroy(); 217``` 218 219### on\('headerReceive'\) 220 221on\(type: 'headerReceive', callback: AsyncCallback<Object\>\): void 222 223Registers an observer for HTTP Response Header events. 224 225> **NOTE** 226> 227> This API has been deprecated. You are advised to use [on\('headersReceive'\)<sup>8+</sup>](#onheadersreceive8) instead. 228 229**System capability**: SystemCapability.Communication.NetStack 230 231**Parameters** 232 233| Name | Type | Mandatory| Description | 234| -------- | ----------------------- | ---- | --------------------------------- | 235| type | string | Yes | Event type. The value is **headerReceive**.| 236| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. | 237 238**Example** 239 240``` 241httpRequest.on('headerReceive', (err, data) => { 242 if (!err) { 243 console.info('header: ' + JSON.stringify(data)); 244 } else { 245 console.info('error:' + JSON.stringify(err)); 246 } 247}); 248``` 249 250 251### off\('headerReceive'\) 252 253off\(type: 'headerReceive', callback?: AsyncCallback<Object\>\): void 254 255Unregisters the observer for HTTP Response Header events. 256 257> **NOTE** 258> 259>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead. 260> 261>2. You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. 262 263**System capability**: SystemCapability.Communication.NetStack 264 265**Parameters** 266 267| Name | Type | Mandatory| Description | 268| -------- | ----------------------- | ---- | ------------------------------------- | 269| type | string | Yes | Event type. The value is **headerReceive**.| 270| callback | AsyncCallback\<Object\> | No | Callback used to return the result. | 271 272**Example** 273 274``` 275httpRequest.off('headerReceive'); 276``` 277 278### on\('headersReceive'\)<sup>8+</sup> 279 280on\(type: 'headersReceive', callback: Callback<Object\>\): void 281 282Registers an observer for HTTP Response Header events. 283 284**System capability**: SystemCapability.Communication.NetStack 285 286**Parameters** 287 288| Name | Type | Mandatory| Description | 289| -------- | ------------------ | ---- | ---------------------------------- | 290| type | string | Yes | Event type. The value is **headersReceive**.| 291| callback | Callback\<Object\> | Yes | Callback used to return the result. | 292 293**Example** 294 295``` 296httpRequest.on('headersReceive', (header) => { 297 console.info('header: ' + JSON.stringify(header)); 298}); 299``` 300 301 302### off\('headersReceive'\)<sup>8+</sup> 303 304off\(type: 'headersReceive', callback?: Callback<Object\>\): void 305 306Unregisters the observer for HTTP Response Header events. 307 308> **NOTE** 309> 310>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. 311 312**System capability**: SystemCapability.Communication.NetStack 313 314**Parameters** 315 316| Name | Type | Mandatory| Description | 317| -------- | ------------------ | ---- | -------------------------------------- | 318| type | string | Yes | Event type. The value is **headersReceive**.| 319| callback | Callback\<Object\> | No | Callback used to return the result. | 320 321**Example** 322 323``` 324httpRequest.off('headersReceive'); 325``` 326 327### once\('headersReceive'\)<sup>8+</sup> 328 329once\(type: 'headersReceive', callback: Callback<Object\>\): void 330 331Registers a one-time observer for HTTP Response Header events. Once triggered, the observer will be removed. This API uses an asynchronous callback to return the result. 332 333**System capability**: SystemCapability.Communication.NetStack 334 335**Parameters** 336 337| Name | Type | Mandatory| Description | 338| -------- | ------------------ | ---- | ---------------------------------- | 339| type | string | Yes | Event type. The value is **headersReceive**.| 340| callback | Callback\<Object\> | Yes | Callback used to return the result. | 341 342**Example** 343 344``` 345httpRequest.once('headersReceive', (header) => { 346 console.info('header: ' + JSON.stringify(header)); 347}); 348``` 349 350## HttpRequestOptions 351 352Specifies the type and value range of the optional parameters in the HTTP request. 353 354**System capability**: SystemCapability.Communication.NetStack 355 356| Name | Type | Mandatory| Description | 357| -------------- | ------------------------------------ | ---- | ---------------------------------------------------------- | 358| method | [RequestMethod](#requestmethod) | No | Request method. | 359| extraData | string \| Object \| ArrayBuffer<sup>8+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>8+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>8+</sup> | 360| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.| 361| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | 362| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | 363 364## RequestMethod 365 366Defines an HTTP request method. 367 368**System capability**: SystemCapability.Communication.NetStack 369 370| Name | Value | Description | 371| :------ | ------- | :------------------ | 372| OPTIONS | OPTIONS | OPTIONS method.| 373| GET | GET | GET method. | 374| HEAD | HEAD | HEAD method. | 375| POST | POST | POST method. | 376| PUT | PUT | PUT method. | 377| DELETE | DELETE | DELETE method. | 378| TRACE | TRACE | TRACE method. | 379| CONNECT | CONNECT | CONNECT method.| 380 381## ResponseCode 382 383Enumerates the response codes for an HTTP request. 384 385**System capability**: SystemCapability.Communication.NetStack 386 387| Name | Value | Description | 388| ----------------- | ---- | ------------------------------------------------------------ | 389| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. | 390| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | 391| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | 392| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | 393| NO_CONTENT | 204 | "No Content." The server has successfully fulfilled the request but there is no additional content to send in the response payload body. | 394| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. | 395| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. | 396| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. | 397| MOVED_PERM | 301 | "Moved Permanently." The requested resource has been assigned a new permanent URI and any future references to this resource will be redirected to this URI.| 398| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. | 399| SEE_OTHER | 303 | "See Other." The response to the request can be found under a different URI. | 400| NOT_MODIFIED | 304 | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified. | 401| USE_PROXY | 305 | "Use Proxy." The requested resource can only be accessed through the proxy. | 402| BAD_REQUEST | 400 | "Bad Request." The request could not be understood by the server due to incorrect syntax. | 403| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication. | 404| PAYMENT_REQUIRED | 402 | "Payment Required." This code is reserved for future use. | 405| FORBIDDEN | 403 | "Forbidden." The server understands the request but refuses to process it. | 406| NOT_FOUND | 404 | "Not Found." The server does not find anything matching the Request-URI. | 407| BAD_METHOD | 405 | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI. | 408| NOT_ACCEPTABLE | 406 | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request. | 409| PROXY_AUTH | 407 | "Proxy Authentication Required." The request requires user authentication with the proxy. | 410| CLIENT_TIMEOUT | 408 | "Request Timeout." The client fails to generate a request within the timeout period. | 411| CONFLICT | 409 | "Conflict." The request cannot be fulfilled due to a conflict with the current state of the resource. Conflicts are most likely to occur in response to a PUT request. | 412| GONE | 410 | "Gone." The requested resource has been deleted permanently and is no longer available. | 413| LENGTH_REQUIRED | 411 | "Length Required." The server refuses to process the request without a defined Content-Length. | 414| PRECON_FAILED | 412 | "Precondition Failed." The precondition in the request is incorrect. | 415| ENTITY_TOO_LARGE | 413 | "Request Entity Too Large." The server refuses to process a request because the request entity is larger than the server is able to process. | 416| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. | 417| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. | 418| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. | 419| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. | 420| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.| 421| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. | 422| GATEWAY_TIMEOUT | 504 | "Gateway Timeout." The server acting as a gateway or proxy does not receive requests from the remote server within the timeout period. | 423| VERSION | 505 | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request. | 424 425## HttpResponse 426 427Defines the response to an HTTP request. 428 429**System capability**: SystemCapability.Communication.NetStack 430 431| Name | Type | Mandatory| Description | 432| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | 433| result | string \| Object \| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string| 434| responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. The error code can be one of the following:<br>- 200: common error<br>- 202: parameter error<br>- 300: I/O error| 435| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];| 436| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. | 437