# @ohos.net.http (Data Request)
The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
> **NOTE**
> 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.
## Modules to Import
```js
import http from '@ohos.net.http';
```
## Example
```js
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
let httpRequest = http.createHttp();
// 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.
// on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8.
httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data.
usingCache: true, // Optional. The default value is true.
priority: 1, // Optional. The default value is 1.
connectTimeout: 60000 // Optional. The default value is 60000, in ms.
readTimeout: 60000, // Optional. The default value is 60000, in ms.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header carries the HTTP response header. Parse the content based on service requirements.
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
}
}
);
```
## http.createHttp
createHttp\(\): HttpRequest
Creates 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.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| ---------- | ----------------------------------------------------------- |
| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.|
**Example**
```js
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
## HttpRequest
Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
### request
request\(url: string, callback: AsyncCallback\\):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------- | ---- | ----------------------- |
| url | string | Yes | URL for initiating an HTTP request.|
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. |
**Example**
```js
httpRequest.request("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### request
request\(url: string, options: HttpRequestOptions, callback: AsyncCallback\):void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
| callback | AsyncCallback\<[HttpResponse](#httpresponse)\> | Yes | Callback used to return the result. |
**Example**
```js
httpRequest.request("EXAMPLE_URL",
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
},
readTimeout: 60000,
connectTimeout: 60000
}, (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('header.Content-Type:' + data.header['Content-Type']);
console.info('header.Status-Line:' + data.header['Status-Line']);
} else {
console.info('error:' + JSON.stringify(err));
}
});
```
### request
request\(url: string, options? : HttpRequestOptions\): Promise
Initiates an HTTP request to a given URL. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------------------ | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
**Return value**
| Type | Description |
| ------------------------------------- | -------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|
**Example**
```js
let promise = httpRequest.request("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
promise.then((data) => {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
console.info('header:' + JSON.stringify(data.header));
console.info('cookies:' + data.cookies); // 8+
console.info('header.Content-Type:' + data.header['Content-Type']);
console.info('header.Status-Line:' + data.header['Status-Line']);
}).catch((err) => {
console.info('error:' + JSON.stringify(err));
});
```
### destroy
destroy\(\): void
Destroys an HTTP request.
**System capability**: SystemCapability.Communication.NetStack
**Example**
```js
httpRequest.destroy();
```
### on\('headerReceive'\)
on\(type: 'headerReceive', callback: AsyncCallback