# @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';
```
## Examples
```js
// Import the http namespace.
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 in extraData 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 parameter is used to transfer data when the POST request is used.
extraData: {
"data": "data to send",
},
expectDataType: http.HttpDataType.STRING, // Optional. This parameter 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.
usingProxy: false, // Optional. By default, network proxy is not used. This field is supported since API version 10.
caPath: "", // Optional. The preset CA certificate is used by default. This field is supported since API version 10.
}, (err, data) => {
if (!err) {
// data.result carries the HTTP response. Parse the response based on service requirements.
console.info('Result:' + JSON.stringify(data.result));
console.info('code:' + JSON.stringify(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:' + JSON.stringify(data.cookies)); // 8+
// Call the destroy() method to release resources after the HttpRequest is complete.
httpRequest.destroy();
} else {
console.info('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after the HttpRequest is complete.
httpRequest.destroy();
}
}
);
```
> **NOTE**
> If the data in **console.info()** contains a newline character, the data will be truncated.
## http.createHttp6+
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.
> **NOTE**
> Call the **destroy()** method to release resources after the HttpRequest is complete.
**System capability**: SystemCapability.Communication.NetStack
**Return value**
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| HttpRequest | An **HttpRequest** object, which contains the **request**, **requestInStream**, **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.
### request6+
request(url: string, callback: AsyncCallback\):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API supports only receiving of data not greater than 5 MB.
**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. |
**Error codes**
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
> **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
**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));
}
});
```
### request6+
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.
> **NOTE**
> This API supports only receiving of data not greater than 5 MB.
**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. |
**Error codes**
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
> **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
**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));
}
});
```
### request6+
request(url: string, options? : HttpRequestOptions): Promise\
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
> **NOTE**
> This API supports only receiving of data not greater than 5 MB.
**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.|
**Error codes**
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
> **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
**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();
```
### requestInStream10+
requestInStream(url: string, callback: AsyncCallback\): void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
**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\<[number](#responsecode)\> | Yes | Callback used to return the result. |
**Error codes**
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
> **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
**Example**
```js
httpRequest.requestInStream("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
### requestInStream10+
requestInStream(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, which is a streaming response.
**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\<[number](#responsecode)\> | Yes | Callback used to return the result. |
**Error codes**
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
> **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
**Example**
```js
httpRequest.requestInStream("EXAMPLE_URL",
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
},
readTimeout: 60000,
connectTimeout: 60000
}, (err, data) => {
if (!err) {
console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
### requestInStream10+
requestInStream(url: string, options? : HttpRequestOptions): Promise\
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response.
**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\<[number](#responsecode)\> | Promise used to return the result.|
**Error codes**
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
| 2300001 | Unsupported protocol. |
| 2300003 | URL using bad/illegal format or missing URL. |
| 2300005 | Couldn't resolve proxy name. |
| 2300006 | Couldn't resolve host name. |
| 2300007 | Couldn't connect to server. |
| 2300008 | Weird server reply. |
| 2300009 | Access denied to remote resource. |
| 2300016 | Error in the HTTP2 framing layer. |
| 2300018 | Transferred a partial file. |
| 2300023 | Failed writing received data to disk/application. |
| 2300025 | Upload failed. |
| 2300026 | Failed to open/read local data from file/application. |
| 2300027 | Out of memory. |
| 2300028 | Timeout was reached. |
| 2300047 | Number of redirects hit maximum amount. |
| 2300052 | Server returned nothing (no headers, no data). |
| 2300055 | Failed sending data to the peer. |
| 2300056 | Failure when receiving data from the peer. |
| 2300058 | Problem with the local SSL certificate. |
| 2300059 | Couldn't use specified SSL cipher. |
| 2300060 | SSL peer certificate or SSH remote key was not OK. |
| 2300061 | Unrecognized or bad HTTP Content or Transfer-Encoding.|
| 2300063 | Maximum file size exceeded. |
| 2300070 | Disk full or allocation exceeded. |
| 2300073 | Remote file already exists. |
| 2300077 | Problem with the SSL CA cert (path? access rights?). |
| 2300078 | Remote file not found. |
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
> **NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
**Example**
```js
let promise = httpRequest.requestInStream("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
header: {
'Content-Type': 'application/json'
}
});
promise.then((data) => {
console.info("requestInStream OK!" + JSON.stringify(data));
}).catch((err) => {
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
});
```
### on('headerReceive')(deprecated)
on(type: 'headerReceive', callback: AsyncCallback\