1# HTTP Data Request 2 3## When to Use 4 5An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. 6 7## Available APIs 8 9The HTTP request function is mainly implemented by the HTTP module. 10 11To use related APIs, you must declare the **ohos.permission.INTERNET** permission. 12 13For details about how to apply for permissions, see [Access Control Development](../security/accesstoken-guidelines.md). 14 15The following table provides only a simple description of the related APIs. For details, see [API Reference](../reference/apis/js-apis-http.md). 16 17| API | Description | 18| ----------------------------------------- | ----------------------------------- | 19| createHttp() | Creates an HTTP request. | 20| request() | Initiates an HTTP request to a given URL. | 21| requestInStream()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.| 22| destroy() | Destroys an HTTP request. | 23| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. | 24| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.| 25| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.| 26| on\('dataReceive'\)<sup>10+</sup> | Registers an observer for events indicating receiving of HTTP streaming responses. | 27| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. | 28| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. | 29| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.| 30| on\('dataReceiveProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. | 31| off\('dataReceiveProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| 32 33## How to Develop request APIs 34 351. Import the **http** namespace from **@ohos.net.http.d.ts**. 362. Call **createHttp()** to create an **HttpRequest** object. 373. Call **httpRequest.on()** to subscribe to HTTP response header events. This API returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements. 384. Call **httpRequest.request()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. 395. Parse the returned result based on service requirements. 406. Call **off()** to unsubscribe from HTTP response header events. 417. Call **httpRequest.destroy()** to release resources after the request is processed. 42 43```ts 44// Import the http namespace. 45import http from '@ohos.net.http'; 46import { BusinessError } from '@ohos.base'; 47 48// Each httpRequest corresponds to an HTTP request task and cannot be reused. 49let httpRequest = http.createHttp(); 50// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events. 51// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. 52httpRequest.on('headersReceive', (header) => { 53 console.info('header: ' + JSON.stringify(header)); 54}); 55httpRequest.request( 56 // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. 57 "EXAMPLE_URL", 58 { 59 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 60 // You can add header fields based on service requirements. 61 header: [{ 62 'Content-Type': 'application/json' 63 }], 64 // This field is used to transfer data when the POST request is used. 65 extraData: "data to send", 66 expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. 67 usingCache: true, // Optional. The default value is true. 68 priority: 1, // Optional. The default value is 1. 69 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 70 readTimeout: 60000, // Optional. The default value is 60000, in ms. 71 usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. 72 usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API 10. 73 }, (err: BusinessError, data: http.HttpResponse) => { 74 if (!err) { 75 // data.result carries the HTTP response. Parse the response based on service requirements. 76 console.info('Result:' + JSON.stringify(data.result)); 77 console.info('code:' + JSON.stringify(data.responseCode)); 78 // data.header carries the HTTP response header. Parse the content based on service requirements. 79 console.info('header:' + JSON.stringify(data.header)); 80 console.info('cookies:' + JSON.stringify(data.cookies)); // 8+ 81 // Call the destroy() method to release resources after HttpRequest is complete. 82 httpRequest.destroy(); 83 } else { 84 console.error('error:' + JSON.stringify(err)); 85 // Unsubscribe from HTTP Response Header events. 86 httpRequest.off('headersReceive'); 87 // Call the destroy() method to release resources after HttpRequest is complete. 88 httpRequest.destroy(); 89 } 90 } 91); 92``` 93 94## How to Develop requestInStream APIs 95 961. Import the **http** namespace from **@ohos.net.http.d.ts**. 972. Call **createHttp()** to create an **HttpRequest** object. 983. Depending on your need, call **on()** of the **HttpRequest** object to subscribe to HTTP response header events as well as events indicating receiving of HTTP streaming responses, progress of receiving HTTP streaming responses, and completion of receiving HTTP streaming responses. 994. Call **requestInStream()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request. 1005. Parse the returned response code as needed. 1016. Call **off()** of the **HttpRequest** object to unsubscribe from the related events. 1027. Call **httpRequest.destroy()** to release resources after the request is processed. 103 104```ts 105// Import the http namespace. 106import http from '@ohos.net.http' 107import { BusinessError } from '@ohos.base'; 108 109// Each httpRequest corresponds to an HTTP request task and cannot be reused. 110let httpRequest = http.createHttp(); 111// Subscribe to HTTP response header events. 112httpRequest.on('headersReceive', (header: Object) => { 113 console.info('header: ' + JSON.stringify(header)); 114}); 115// Subscribe to events indicating receiving of HTTP streaming responses. 116let res = ''; 117httpRequest.on('dataReceive', (data: ArrayBuffer) => { 118 res += data; 119 console.info('res: ' + res); 120}); 121// Subscribe to events indicating completion of receiving HTTP streaming responses. 122httpRequest.on('dataEnd', () => { 123 console.info('No more data in response, data receive end'); 124}); 125// Subscribe to events indicating progress of receiving HTTP streaming responses. 126class Data { 127 receiveSize: number = 0 128 totalSize: number = 0 129} 130httpRequest.on('dataReceiveProgress', (data: Data) => { 131 console.log("dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize); 132}); 133 134let streamInfo: http.HttpRequestOptions = { 135 method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET. 136 // You can add header fields based on service requirements. 137 header: ['Content-Type', 'application/json'], 138 // This field is used to transfer data when the POST request is used. 139 extraData: ["data", "data to send"], 140 expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. 141 usingCache: true, // Optional. The default value is true. 142 priority: 1, // Optional. The default value is 1. 143 connectTimeout: 60000 // Optional. The default value is 60000, in ms. 144 readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission. 145 usingProtocol: http.HttpProtocol.HTTP1_1 // Optional. The default protocol type is automatically specified by the system. 146} 147 148httpRequest.requestInStream( 149 // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. 150 "EXAMPLE_URL", 151 streamInfo, (err: BusinessError, data: number) => { 152 console.error('error:' + JSON.stringify(err)); 153 console.info('ResponseCode :' + JSON.stringify(data)); 154 // Unsubscribe from HTTP Response Header events. 155 httpRequest.off('headersReceive'); 156 // Unregister the observer for events indicating receiving of HTTP streaming responses. 157 httpRequest.off('dataReceive'); 158 // Unregister the observer for events indicating progress of receiving HTTP streaming responses. 159 httpRequest.off('dataReceiveProgress'); 160 // Unregister the observer for events indicating completion of receiving HTTP streaming responses. 161 httpRequest.off('dataEnd'); 162 // Call the destroy() method to release resources after HttpRequest is complete. 163 httpRequest.destroy(); 164} 165); 166``` 167 168