>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
```
import http from '@ohos.net.http';
```
## Complete Example
```
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HttpRequestTask object and cannot be reused.
let httpRequest = http.createHttp();
// This API is used to subscribe to the HTTP response header, which is returned earlier than httpRequest. It is up to you whether to listen for HTTP Response Header events.
// on('headerReceive', AsyncCallback) will be replaced by on('headersReceive', Callback) in API version 8. 8+
httpRequest.on('headersReceive', (data) => {
console.info('header: ' + data.header);
});
httpRequest.request(
// Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL. You can set the parameters of the GET request in extraData.
"EXAMPLE_URL",
{
method: 'POST', // Optional. The default value is GET.
// Add the header field based on your service requirements.
header: {
'Content-Type': 'application/json'
},
// This field is used to transfer content when the POST request is used. You can set request parameters in extraData as needed.
extraData: {
"data": "data to send",
},
connectTimeout: 60000, // Optional. The default value is **60000**, in ms.
readTimeout: 60000, // Optional. The default value is **60000**, in ms.
},(err, data) => {
if (!err) {
// data.result contains the HTTP response. It is up to you whether to parse the content.
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
// data.header contains the HTTP response header. It is up to you whether to parse the content.
console.info('header:' + data.header);
console.info('cookies:' + data.cookies); // 8+
} else {
console.info('error:' + err);
// Call the destroy function to destroy the request after use.
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.
| HttpRequest | An **HttpRequest **object, which contains the **request**, **destroy**, **on**, or **off** method.|
**Example**
```
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
## HttpRequest
Defines an **HttpRequest** object. Before invoking HttpRequest APIs, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object.
>1. This API has been deprecated. You are advised to use [off\('headersReceive'\)<sup>8+</sup>](#offheadersreceive8) instead.
>
>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.
>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.
Registers 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.
| method | [RequestMethod](#requestmethod) | No | Request method. |
| 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> |
| header | Object | No | HTTP request header. The default value is {'Content-Type': 'application/json'}.|
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
| 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. |
| RESET | 205 | "Reset Content." The server has successfully fulfilled the request and desires that the user agent reset the content. |
| PARTIAL | 206 | "Partial Content." The server has successfully fulfilled the partial GET request for a given resource. |
| MULT_CHOICE | 300 | "Multiple Choices." The requested resource corresponds to any one of a set of representations. |
| 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.|
| MOVED_TEMP | 302 | "Moved Temporarily." The requested resource is moved temporarily to a different URI. |
| SEE_OTHER | 303 | "See Other." The response to the request can be found under a different URI. |
| NOT_MODIFIED | 304 | "Not Modified." The client has performed a conditional GET request and access is allowed, but the content has not been modified. |
| USE_PROXY | 305 | "Use Proxy." The requested resource can only be accessed through the proxy. |
| BAD_REQUEST | 400 | "Bad Request." The request could not be understood by the server due to incorrect syntax. |
| UNAUTHORIZED | 401 | "Unauthorized." The request requires user authentication. |
| PAYMENT_REQUIRED | 402 | "Payment Required." This code is reserved for future use. |
| FORBIDDEN | 403 | "Forbidden." The server understands the request but refuses to process it. |
| NOT_FOUND | 404 | "Not Found." The server does not find anything matching the Request-URI. |
| BAD_METHOD | 405 | "Method Not Allowed." The method specified in the request is not allowed for the resource identified by the Request-URI. |
| NOT_ACCEPTABLE | 406 | "Not Acceptable." The server cannot fulfill the request according to the content characteristics of the request. |
| PROXY_AUTH | 407 | "Proxy Authentication Required." The request requires user authentication with the proxy. |
| CLIENT_TIMEOUT | 408 | "Request Timeout." The client fails to generate a request within the timeout period. |
| 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. |
| GONE | 410 | "Gone." The requested resource has been deleted permanently and is no longer available. |
| LENGTH_REQUIRED | 411 | "Length Required." The server refuses to process the request without a defined Content-Length. |
| PRECON_FAILED | 412 | "Precondition Failed." The precondition in the request is incorrect. |
| 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. |
| REQ_TOO_LONG | 414 | "Request-URI Too Long." The Request-URI is too long for the server to process. |
| UNSUPPORTED_TYPE | 415 | "Unsupported Media Type." The server is unable to process the media format in the request. |
| INTERNAL_ERROR | 500 | "Internal Server Error." The server encounters an unexpected error that prevents it from fulfilling the request. |
| NOT_IMPLEMENTED | 501 | "Not Implemented." The server does not support the function required to fulfill the request. |
| BAD_GATEWAY | 502 | "Bad Gateway." The server acting as a gateway or proxy receives an invalid response from the upstream server.|
| UNAVAILABLE | 503 | "Service Unavailable." The server is currently unable to process the request due to a temporary overload or system maintenance. |
| 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. |
| VERSION | 505 | "HTTP Version Not Supported." The server does not support the HTTP protocol version used in the request. |
| 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|
| 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|
| 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'];|
| cookies<sup>8+</sup> | Array\<string\> | Yes | Cookies returned by the server. |
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates that the default data network is activated.|
**Example**
```javascript
connection.hasDefaultNet(function(error,has){
console.log(JSON.stringify(error))
console.log(has)
})
```
## connection.hasDefaultNet
hasDefaultNet(): Promise\<boolean>
Checks whether the default data network is activated. This API uses a promise to return the result.
| netSpecifier | [NetSpecifier](#netspecifier) | No | Network specifier. If this parameter is not set, the default network is used. |
| timeout | number | No | Timeout interval for obtaining the network specified by **netSpecifier**. This parameter is valid only when **netSpecifier** is set.|
| type | string | Yes | Event type. The value is fixed to **netCapabilitiesChange**.<br>**netCapabilitiesChange**: event indicating that he network capabilities have changed.|
| callback | Callback<{netHandle:[NetHandle](#nethandle),netCap:[NetCapabilities](#netcapabilities)}> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{netHandle:[NetHandle](#nethandle),connectionProperties:[ConnectionProperties](#connectionproperties)}> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netBlockStatusChange**.<br>**netBlockStatusChange**: event indicating a change in the network blocking status.|
| callback | Callback<{ netHandle: [NetHandle](#nethandle), blocked: boolean }> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netLost**.<br>netLost: event indicating that the network is interrupted or normally disconnected.|
| callback | Callback\<[NetHandle](#nethandle)> | Yes | Callback used to return the result. |
| type | string | Yes | Event type. The value is fixed to **netUnavailable**.<br>**netUnavailable**: event indicating that the network is unavailable.|
| callback | Callback\<void> | Yes | Callback used to return the result. |
| netCapabilities | [NetCapabilities](#netcapabilities) | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
| NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.|
| NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.|
| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.|
| NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).|
| NET_CAPABILITY_VALIDATED | 16 | The network is available. |
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Defines a **UDPSocket** connection. Before invoking UDPSocket APIs, you need to call [socket.constructUDPSocketInstance](#socketconstructudpsocketinstance) to create a **UDPSocket** object.
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
udp.send({
data:'Hello, server!',
address: {
address:'192.168.xx.xxx',
port:xxxx,
family:1
}
}, err=> {
if (err) {
console.log('send fail');
return;
}
console.log('send success');
})
```
### send
send\(options: UDPSendOptions\): Promise<void\>
Sends data over a UDPSocket connection. This API uses a promise to return the result.
| options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).|
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).|
>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.
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
Enables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>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.
| type | string | Yes | Event type.<br>- **listening**: data packet message event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. |
**Example**
```
let udp = socket.constructUDPSocketInstance();
let callback1 = () =>{
console.log("on listening, success");
}
udp.on('listening', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('listening', callback1);
udp.off('listening');
let callback2 = () =>{
console.log("on close, success");
}
udp.on('close', callback2);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
>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.
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
| port | number | No | Port number. The value ranges from **0** to **65535**. If this parameter is not specified, the system randomly allocates a port. |
| family | number | No | Network protocol type.<br>- **1**: IPv4<br>- **2**: IPv6<br>The default value is **1**.|
## UDPSendOptions
Defines the parameters for sending data over the UDPSocket connection.
Defines a TCPSocket connection. Before invoking TCPSocket APIs, you need to call [socket.constructTCPSocketInstance](#socketconstructtcpsocketinstance) to create a **TCPSocket** object.
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result.
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result.
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).|
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).|
>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.
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
>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.
| type | string | Yes | Event type.<br>- **connect**: connection event<br>- **close**: close event|
| callback | Callback\<void\> | No | Callback used to return the result. |
**Example**
```
let tcp = socket.constructTCPSocketInstance();
let callback1 = () =>{
console.log("on connect success");
}
tcp.on('connect', callback1);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('connect', callback1);
tcp.off('connect');
let callback2 = () =>{
console.log("on close success");
}
tcp.on('close', callback2);
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
>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.
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
| encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.|
## TCPExtraOptions
Defines other properties of the TCPSocket connection.
| keepAlive | boolean | No | Whether to keep the connection alive. The default value is **false**. |
| OOBInline | boolean | No | Whether to enable OOBInline. The default value is **false**. |
| TCPNoDelay | boolean | No | Whether to enable no-delay on the TCPSocket connection. The default value is **false**. |
| socketLinger | Object | Yes | Socket linger.<br>- **on**: whether to enable socket linger. The value true means to enable socket linger and false means the opposite.<br>- **linger**: linger time, in ms. The value ranges from **0** to **65535**.<br>Specify this parameter only when **on** is set to **true**.|
| receiveBufferSize | number | No | Size of the receive buffer, in bytes. |
| sendBufferSize | number | No | Size of the send buffer, in bytes. |
| reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. |
| socketTimeout | number | No | Timeout duration of the UDPSocket connection, in ms. |
>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.
>
>Newly added APIs are defined but not implemented in OpenHarmony 3.1 Release. They will be available for use in OpenHarmony 3.1 MR.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event.
Creates a WebSocket connection. You can use this API to create or close a WebSocket connection, send data over it, or enable or disable listening for the **open**, **close**, **message**, and **error** events.
| [WebSocket](#websocket) | A **WebSocket** object, which contains the **connect**, **send**, **close**, **on**, or **off** method.|
**Example**
```
let ws = webSocket.createWebSocket();
```
## WebSocket
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#webSocketcreatewebsocket) to create a **WebSocket** object.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
>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.
// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
>The data in **AsyncCallback** can be in the format of string\(API 6\) or ArrayBuffer\(API 8\).
>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.
>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.
>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.
| header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|
## WebSocketCloseOptions
Defines the optional parameters carried in the request for closing a WebSocket connection.