Intelligent Assistant
Chat with our virtual assistant to get answers promptly.
This module provides the HTTP data request capability. With this capability, your app can send data requests using HTTP. Common HTTP methods include GET, POST, HEAD, PUT, DELETE, PATCH, and OPTIONS.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
import { rcp } from '@kit.RemoteCommunicationKit'; createSession(sessionConfiguration?: SessionConfiguration): Session
Creates an HTTP session. This is the main method for starting an HTTP interaction. You can use this API and SessionConfiguration together to create and configure a session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| sessionConfiguration | SessionConfiguration | No | Configurations to be applied to a session. |
Returns:
| Type | Description |
|---|---|
| Session | Represents a session, for sending HTTP requests and managing the lifecycle of the session. Starting from version 5.1.0(18), a maximum of 1024 session instances can be created. To ensure efficient resource utilization, your app should promptly close sessions after completing network requests using these created session instances. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
| 1007900994 | Sessions number reached limit. |
Example:
const session = rcp.createSession();
Represents a communication session that can be used to initiate HTTP requests. It supports various HTTP methods, such as FETCH, GET, POST, PUT, HEAD, DELETE, CANCEL and CLOSE.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| id | string | Yes | No | Session identifier. |
| configuration | SessionConfiguration | undefined | Yes | No | Session configurations. |
fetch(request: Request): Promise<Response>
Sends an HTTP request and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| request | Request | Yes | Request to be sent. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
let req = new rcp.Request('http://example.com/fetch', 'POST');
session.fetch(req).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); fetchForSendable(request: Request): Promise<ResponseSendable>
Sends an HTTP request and obtains an HTTP response from the server. The response message supports Sendable. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| request | Request | Yes | Request to be sent. |
Returns:
| Type | Description |
|---|---|
| Promise<ResponseSendable> | Promise object, which is used to return the response object from the server. The response message supports Sendable. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { ArkTSUtils, collections, taskpool, util } from '@kit.ArkTS';
@Concurrent
async function taskFunc(sendableResponse: rcp.ResponseSendable) {
console.info(`sendableResponse: ${ArkTSUtils.ASON.stringify(sendableResponse)}`);
// Print the body data of the Sendable type.
if (ArkTSUtils.isSendable(sendableResponse.body) && sendableResponse.body != undefined) {
const decoder = util.TextDecoder.create('utf-8');
let arr: collections.Uint8Array = new collections.Uint8Array(sendableResponse.body);
let str = decoder.decodeToString(arr as Object as Uint8Array).trim();
console.info(`body:${ArkTSUtils.ASON.stringify(str)}`);
}
}
async function test() {
try {
const session = rcp.createSession();
let request = new rcp.Request('https://www.example.com'); // Replace the URL with the actual one.
let sendableResponse = await session.fetchForSendable(request);
let isSendable = ArkTSUtils.isSendable(sendableResponse);
if (isSendable) {
console.info(`Succeeded in getting the response, the response is sendable`);
} else {
console.info(`Succeeded in getting the response, the response is not sendable`);
}
let task: taskpool.Task = new taskpool.Task(taskFunc, sendableResponse);
await taskpool.execute(task);
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
}
} get(url: URLOrString, destination?: ResponseBodyDestination): Promise<Response>
Sends an HTTP GET request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP GET request. |
| destination | ResponseBodyDestination | No | Destination of the HTTP response. Since: 5.0.0(12) |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
session.get('http://example.com/get').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); post(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>
Sends an HTTP POST request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP POST request. |
| content | RequestContent | No | Request content. The default value is undefined. |
| destination | ResponseBodyDestination | No | Destination of the HTTP response. Since: 5.0.0(12) |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
session.post('http://example.com/post', 'data to send').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); put(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>
Sends an HTTP PUT request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP PUT request. |
| content | RequestContent | No | Request content. The default value is undefined. |
| destination | ResponseBodyDestination | No | Destination of the HTTP response. Since: 5.0.0(12) |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
session.put('http://example.com/put', 'data to send').then((response) => {
console.info(`Succeeded in getting the response ${response.toString()}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); downloadToFile(url: URLOrString, downloadTo: DownloadToFile): Promise<Response>
Sends an HTTP DOWNLOADTOFILE request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP DOWNLOADTOFILE request. |
| downloadTo | DownloadToFile | Yes | Location in the local file system for storing files downloaded from the server. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
let downloadToFile: rcp.DownloadToFile = {
kind: 'folder',
path: '/path/dir' // Set the path based on your service needs.
} as rcp.DownloadToFile
const session = rcp.createSession();
session.downloadToFile('http://www.example.com', downloadToFile).then((response) => {
console.info(`Succeeded in getting the response ${response.toString()}`);
}).catch((err: BusinessError) => {
console.error(`DownloadToFile failed, the error code is ${err.code}, error data is ${err.data}`);
}); uploadFromFile(url: URLOrString, uploadFrom: UploadFromFile): Promise<Response>
Sends an HTTP UPLOADFROMFILE request carrying default HTTP parameters to complete file upload and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP UPLOADFROMFILE request. |
| uploadFrom | UploadFromFile | Yes | Request for uploading a file from the local computer to the server. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
let fileDir = '/path/dir/'; // Define the path based on the service requirements.
let uploadFromFile: rcp.UploadFromFile = {
fileOrPath: fileDir
};
const session = rcp.createSession();
session.uploadFromFile('http://example.com/head', uploadFromFile).then((response) => {
console.info(`Succeeded in getting the response ${response.toString()}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); downloadToStream(url: URLOrString, downloadTo: DownloadToStream): Promise<Response>
Sends an HTTP DOWNLOADTOSTREAM request carrying default HTTP parameters to request downloading data in stream mode from the server and obtains an HTTP response. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP DOWNLOADTOSTREAM request. |
| downloadTo | DownloadToStream | Yes | Request for downloading a file from the server to the client and writing the file to a data stream. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
const streamData: rcp.WriteStream = {
write(buffer: ArrayBuffer): Promise<void | number> {
return Promise.resolve(buffer.byteLength)
}
};
let downloadToStream: rcp.DownloadToStream = {
kind: 'stream',
stream: streamData
}
const session = rcp.createSession();
session.downloadToStream('http://example.com/head', downloadToStream).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); uploadFromStream(url: URLOrString, uploadFrom: UploadFromStream): Promise<Response>
Sends an HTTP UPLOADFROMSTREAM request carrying default HTTP parameters to upload data in stream mode to the server and obtains an HTTP response. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP UPLOADFROMSTREAM request. |
| uploadFrom | UploadFromStream | Yes | Request for uploading data from an input stream to the server. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
let uploadFromStream: rcp.UploadFromStream = {
stream: object // Define an object of the Stream, ReadStream, or SyncReadStream type.
}
const session = rcp.createSession();
session.uploadFromStream('http://example.com/head', uploadFromStream).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); head(url: URLOrString): Promise<Response>
Sends an HTTP HEAD request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP HEAD request. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
session.head('http://example.com/head').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); delete(url: URLOrString): Promise<Response>
Sends an HTTP DELETE request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP DELETE request. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
session.delete('http://example.com/delete').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); cancel(requestToCancel?: Request | Request[]): void
Cancels a specified request or all ongoing requests in a session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
let req = new rcp.Request('http://example.com/fetch', 'GET');
session.fetch(req).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
session.cancel(req);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); close(): void
Closes a session. This API frees up resources related to this session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
let req = new rcp.Request('http://example.com/fetch', 'GET');
session.fetch(req).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
session.close();
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
session.close();
}); getDefaultSession(): DefaultSession
Obtains the default HTTP session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Returns:
| Type | Description |
|---|---|
| DefaultSession | Default session, which is used to send or cancel an HTTP request. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession(); Provides a default session for sending HTTP requests. If session customization is not required, you can simply use DefaultSession to initiate network requests.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
fetch(request: Request): Promise<Response>
Sends an HTTP request and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| request | Request | Yes | Request to be sent. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession();
let req = new rcp.Request('http://example.com/fetch', 'POST');
defaultSession.fetch(req).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); fetchForSendable(request: Request): Promise<ResponseSendable>
Sends an HTTP request and obtains an HTTP response from the server. The response message supports Sendable. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| request | Request | Yes | Request to be sent. |
Returns:
| Type | Description |
|---|---|
| Promise<ResponseSendable> | Promise object, which is used to return the response object from the server. The response message supports Sendable. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { ArkTSUtils, collections, taskpool, util } from '@kit.ArkTS';
@Concurrent
async function taskFunc(sendableResponse: rcp.ResponseSendable) {
console.info(`sendableResponse: ${ArkTSUtils.ASON.stringify(sendableResponse)}`);
// Print the body data of the Sendable type.
if (ArkTSUtils.isSendable(sendableResponse.body) && sendableResponse.body != undefined) {
const decoder = util.TextDecoder.create('utf-8');
let arr: collections.Uint8Array = new collections.Uint8Array(sendableResponse.body);
let str = decoder.decodeToString(arr as Object as Uint8Array).trim();
console.info(`body:${ArkTSUtils.ASON.stringify(str)}`);
}
}
async function test() {
try {
const defaultSession = rcp.getDefaultSession();
let request = new rcp.Request('https://www.example.com'); // Replace the URL with the actual one.
let sendableResponse = await defaultSession.fetchForSendable(request);
let isSendable = ArkTSUtils.isSendable(sendableResponse);
if (isSendable) {
console.info(`Succeeded in getting the response, the response is sendable`);
} else {
console.info(`Succeeded in getting the response, the response is not sendable`);
}
let task: taskpool.Task = new taskpool.Task(taskFunc, sendableResponse);
await taskpool.execute(task);
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
}
} get(url: URLOrString, destination?: ResponseBodyDestination): Promise<Response>
Sends an HTTP GET request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP GET request. |
| destination | ResponseBodyDestination | No | Destination of the HTTP response. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession();
defaultSession.get('http://example.com/get').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); post(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>
Sends an HTTP POST request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP POST request. |
| content | RequestContent | No | Request content. The default value is undefined. |
| destination | ResponseBodyDestination | No | Destination of the HTTP response. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession();
defaultSession.post('http://example.com/post', 'data to send').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); put(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>
Sends an HTTP PUT request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP PUT request. |
| content | RequestContent | No | Request content. The default value is undefined. |
| destination | ResponseBodyDestination | No | Destination of the HTTP response. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession();
defaultSession.put('http://example.com/put', 'data to send').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); downloadToFile(url: URLOrString, downloadTo: DownloadToFile): Promise<Response>
Sends an HTTP DOWNLOADTOFILE request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP DOWNLOADTOFILE request. |
| downloadTo | DownloadToFile | Yes | Location in the local file system for storing files downloaded from the server. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
let downloadToFile: rcp.DownloadToFile = {
kind: 'folder',
path: '/path/dir' // Set the path based on your service needs.
} as rcp.DownloadToFile
const defaultSession = rcp.getDefaultSession();
defaultSession.downloadToFile('http://www.example.com', downloadToFile).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`DownloadToFile failed, the error code is ${err.code}, error data is ${err.data}`);
}); uploadFromFile(url: URLOrString, uploadFrom: UploadFromFile): Promise<Response>
Sends an HTTP UPLOADFROMFILE request carrying default HTTP parameters to complete file upload and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP UPLOADFROMFILE request. |
| uploadFrom | UploadFromFile | Yes | Request for uploading a file from the local computer to the server. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
let fileDir = '/path/dir/'; // Define the path based on the service requirements.
let uploadFromFile: rcp.UploadFromFile = {
fileOrPath: fileDir
};
const defaultSession = rcp.getDefaultSession();
defaultSession.uploadFromFile('http://example.com/head', uploadFromFile).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); downloadToStream(url: URLOrString, downloadTo: DownloadToStream): Promise<Response>
Sends an HTTP DOWNLOADTOSTREAM request carrying default HTTP parameters to request downloading data in stream mode from the server and obtains an HTTP response. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP DOWNLOADTOSTREAM request. |
| downloadTo | DownloadToStream | Yes | Request for downloading a file from the server to the client and writing the file to a data stream. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit'
const streamData: rcp.WriteStream = {
write(buffer: ArrayBuffer): Promise<void | number> {
return Promise.resolve(buffer.byteLength)
}
};
let downloadToStream: rcp.DownloadToStream = {
kind: 'stream',
stream: streamData
}
const defaultSession = rcp.getDefaultSession();
defaultSession.downloadToStream('http://example.com/head', downloadToStream).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); uploadFromStream(url: URLOrString, uploadFrom: UploadFromStream): Promise<Response>
Sends an HTTP UPLOADFROMSTREAM request carrying default HTTP parameters to upload data in stream mode to the server and obtains an HTTP response. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP UPLOADFROMSTREAM request. |
| uploadFrom | UploadFromStream | Yes | Request for uploading data from an input stream to the server. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
let uploadFromStream: rcp.UploadFromStream = {
stream: object // Define an object of the Stream, ReadStream, or SyncReadStream type.
}
const defaultSession = rcp.getDefaultSession();
defaultSession.uploadFromStream('http://example.com/head', uploadFromStream).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); head(url: URLOrString): Promise<Response>
Sends an HTTP HEAD request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP HEAD request. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession();
defaultSession.head('http://example.com/head').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); delete(url: URLOrString): Promise<Response>
Sends an HTTP DELETE request carrying default HTTP parameters and obtains an HTTP response from the server. This API uses a promise to return the result.
Required permissions: ohos.permission.INTERNET (If the cellular option of PathPreference is used, the ohos.permission.GET_NETWORK_INFO permission is also required.)
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL of the target resource in the HTTP DELETE request. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession();
defaultSession.delete('http://example.com/delete').then((response) => {
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); cancel(requestToCancel?: Request | Request[]): void
Cancels a specified request or all ongoing requests in a session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const defaultSession = rcp.getDefaultSession();
let req = new rcp.Request('http://example.com/fetch', 'GET');
defaultSession.fetch(req).then((response) => {
console.info(`Succeeded in getting the response ${response}`);
defaultSession.cancel(req);
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); Provides the interceptor handler.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
handle(context: RequestContext): Promise<Response>
Entry point function of the request handler. Each interceptor calls the handle method of the RequestHandler at the next level to trigger the intercept function of the next-level interceptor, which ultimately triggers a request to the server. This API uses a promise to return the result.
For example, the interceptor [A, B, C, D] is constructed as A {handler->B{handler->C{handler-D{handler->system capability}}}}.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | RequestContext | Yes | Request context. |
Returns:
| Type | Description |
|---|---|
| Promise<Response> | Promise object, which is used to return the response object from the server. |
Example:
For details, please refer to the code example of Interceptor.
Defines the interceptor request context.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Defines an interceptor.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
intercept(context: RequestContext, next: RequestHandler): Promise<Response>
Interceptor, which is used to modify requests, modify responses, or directly return responses. It uses a promise to return the result asynchronously.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | RequestContext | Yes | Request context. |
| next | RequestHandler | Yes | Next request handler. |
Returns:
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
class ResponseCache {
private readonly cache: Record<string, rcp.Response> = {};
getResponse(url: string): rcp.Response {
return this.cache[url];
}
setResponse(url: string, response: rcp.Response): void {
this.cache[url] = response;
}
}
class ResponseCachingInterceptor implements rcp.Interceptor {
private readonly cache: ResponseCache;
constructor(cache: ResponseCache) {
this.cache = cache;
}
async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
const url = context.request.url.href;
const responseFromCache = this.cache.getResponse(url);
if (responseFromCache) {
return Promise.resolve(responseFromCache);
}
const promise = next.handle(context);
promise.then((resp) => {
resp.statusCode;
cache.setResponse(url, resp);
});
return promise;
}
}
const cache = new ResponseCache();
function testInterceptor() {
const session = rcp.createSession({
interceptors: [new ResponseCachingInterceptor(cache)]
});
session.get('https://www.example.com').then((response: rcp.Response) => {
console.info(`Succeeded in getting the response. The statusCode of the response is ${response.statusCode}`);
}).catch((err: BusinessError) => {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
});
let request = new rcp.Request('https://www.example.com', 'GET');
session.fetch(request).then((response: rcp.Response) => {
console.info(`Succeeded in fetching the response. The statusCode of the response is ${response.statusCode}`);
}).catch((err: BusinessError) => {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
});
} Defines the configuration parameters of a session, providing detailed control over various aspects of the HTTP session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| interceptors | Interceptor[] | No | Yes | Request/Response interceptor. Since: 5.0.0(12) |
| requestConfiguration | Configuration | No | Yes | Settings of HTTP requests associated with the session, including transfer, proxy, DNS, connection, and security settings. |
| baseAddress | URLOrString | No | Yes | Base URL in a session. You can define a common base URL for multiple requests in a session. If a request URL is not an absolute URL, the base URL is appended before the request URL. For example, in the URL https://example.com?name=value, https://example.com is the base URL and ?name=value is the request URL. |
| headers | RequestHeaders | No | Yes | Custom headers of HTTP requests sent in a session. You can customize headers based on your service needs. |
| cookies | RequestCookies | No | Yes | Custom cookies that you can include in HTTP requests associated with a session based on your service needs. Cookies must be manually configured to record user behavior. |
| sessionListener | SessionListener | No | Yes | Listener that you can use to listen on cancellation and closing events of a specified session, so you can handle session-related events for your app. |
| connectionConfiguration | ConnectionConfiguration | No | Yes | Connection settings, including the total number of concurrent TCP connections allowed in a session and the maximum number of concurrent TCP connections allowed to a single host. Since: 5.0.0(12) |
| cacheControl | CacheControl | No | Yes | Cache settings. This configuration is used to control the cache verification policy in a session, affecting how the server or proxy responds to requests. Since: 6.0.0(20) |
| cookieRepository | CookieRepository | No | Yes | Cookie repository. All requests within a session share the same cookie repository. If this parameter is configured, requests within this session will actually be handled by DefaultSession. Since: 6.1.0(23) |
| sessionPathPreference | SessionPathPreference | No | Yes | Session path preferences. The default value is auto, indicating the default path. The session path preference cannot conflict with the request path preference. If this parameter is not set to auto and the pathPreference of the request in the session is also not set to auto, error 1007900401 will be reported when the request is initiated. Since: 26.0.0 |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
let cookieRepository = rcp.CookieRepository.create();
const sessionConfig: rcp.SessionConfiguration = {
requestConfiguration: {
transfer: {
autoRedirect: true,
timeout: {
connectMs: 5000,
transferMs: 10000
}
},
tracing: {
verbose: true
}
},
baseAddress: 'http://api.example.com',
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
},
cookies: {
'user': 'john_doe',
'session_id': 'abc123'
},
sessionListener: {
onCanceled: () => console.info('Session was cancelled'),
onClosed: () => console.info('Session was closed')
},
cookieRepository: cookieRepository,
// ...
};
const session = rcp.createSession(sessionConfig); Parameter example of interceptors:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
class ResponseCache {
private readonly cache: Record<string, rcp.Response> = {};
getResponse(url: string): rcp.Response {
return this.cache[url];
}
setResponse(url: string, response: rcp.Response): void {
this.cache[url] = response;
}
}
class ResponseCachingInterceptor implements rcp.Interceptor {
private readonly cache: ResponseCache;
constructor(cache: ResponseCache) {
this.cache = cache;
}
async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
const url = context.request.url.href;
const responseFromCache = this.cache.getResponse(url);
if (responseFromCache) {
return Promise.resolve(responseFromCache);
}
const promise = next.handle(context);
promise.then((resp) => {
this.cache.setResponse(url, resp);
});
return promise;
}
}
const cache = new ResponseCache();
function testInterceptor() {
const session = rcp.createSession({
interceptors: [new ResponseCachingInterceptor(cache)]
});
session.get('https://www.example.com').then((response: rcp.Response) => {
console.info(`Succeeded in getting the response. The statusCode of the response is ${response.statusCode}`);
}).catch((err: BusinessError) => {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
});
let request = new rcp.Request('https://www.example.com', 'GET');
session.fetch(request).then((response: rcp.Response) => {
console.info(`Succeeded in fetching the response. The statusCode of the response is ${response.statusCode}`);
}).catch((err: BusinessError) => {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
});
} Defines parameters that you can use to define HTTP requests in a session, including transmission, tracing, proxy, DNS, and security settings.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| transfer | TransferConfiguration | No | Yes | Data transmission settings for HTTP request processing, including automatic redirection and timeout settings. |
| tracing | TracingConfiguration | No | Yes | Tracing settings of HTTP requests, that can help you perform debugging and performance analysis. |
| proxy | ProxyConfiguration | No | Yes | Proxy settings for a session. The options are system, no-proxy, and WebProxy. |
| dns | DnsConfiguration | No | Yes | DNS settings, where you can either customize your DNS rule or use DNS over HTTPS. |
| security | SecurityConfiguration | No | Yes | Security settings, including certificate and server identity verification settings. |
| processing | ProcessingConfiguration | No | Yes | Response processing configuration. Since: 5.0.0(12) |
| cache | ResponseCache | No | Yes | HTTP caching settings. Since: 6.0.0(20) |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const cache: rcp.ResponseCache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir/' // Specify the cache path based on your service needs.
}
});
const requestConfig: rcp.Configuration = {
transfer: {
autoRedirect: true,
timeout: {
connectMs: 5000,
transferMs: 10000
},
assumesHTTP3Capable: true,
pathPreference: 'cellular'
},
tracing: {
verbose: true
},
proxy: 'system',
dns: {
dnsRules: [
{ host: 'https://example.com', port: 443, ipAddresses: ['192.168.1.1', '192.168.1.2'] }
]
},
security: {
certificate: {
content: '-----BEGIN CERTIFICATE-----\n...',
type: 'PEM',
key: '/path/dir/', // Change the key based on your service needs.
keyPassword: 'your-password'
},
serverAuthentication: {
credential: {
username: 'your-username',
password: 'your-password'
},
authenticationType: 'basic'
}
},
cache: cache
};
// Create a session using the configuration.
const session = rcp.createSession({ requestConfiguration: requestConfig }); Sets the total number of concurrent TCP connections and the maximum number of TCP connections allowed to a single host in a session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| maxConnectionsPerHost | number | Yes | Yes | Maximum number of concurrent TCP connections allowed to a single host (identified by the combination of the host name and port number). Value range: [1, 2147483647] Default value: 6 |
| maxTotalConnections | number | Yes | Yes | Maximum number of concurrent TCP connections allowed in a session. Value range: [1, 2147483647] Default value: 64 |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const connectionConfig: rcp.ConnectionConfiguration = {
maxConnectionsPerHost: 6,
maxTotalConnections: 64
}
const session = rcp.createSession({ connectionConfiguration: connectionConfig }); Enables settings of TCP options.
When any of the keepIdleSec, keepCnt, and keepIntervalSec parameters is set, the client sends a probe packet proactively. Parameters that are not set will use their default value. If the server does not respond to the probe packet within the specified duration in seconds (keepIdleSec + (keepCnt + 1) x keepIntervalSec), the TCP connection will be terminated.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| keepIdleSec | number | No | Yes | A timer that, when triggered, initiates the sending of a probe packet over the TCP connection. Unit: second Value range: [1, 7200] Default value: 7200 |
| userTimeoutMs | number | No | Yes | Timeout interval. If no acknowledgment from the server is received for the transmitted data within this interval, the TCP connection will be terminated. Unit: millisecond Value range: [1, 3600000] Default value: It is the same as the value of Timeout.transferMs. |
| keepCnt | number | No | Yes | Number of times that probe packets are sent. Unit: integer Value range: [1, 9] Default value: 9 |
| keepIntervalSec | number | No | Yes | Interval between each two probe packets. Unit: second Value range: [1, 75] Default value: 75 |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const transferConfig: rcp.TransferConfiguration = {
tcp: {
keepIdleSec: 20,
userTimeoutMs: 3000,
keepCnt: 6,
keepIntervalSec: 30,
}
};
// Create a session using the configuration.
const session = rcp.createSession({
requestConfiguration: {
transfer: transferConfig
}
});
// Create a request using the configuration.
const request = new rcp.Request('https://example.com');
request.configuration = {
transfer: transferConfig
}; Cookie repository, which can automatically captures cookies from HTTP responses and includes cookies in requests, while also supporting manual cookie management. The cookie repository persists to local storage every 30 seconds. Alternatively, you can trigger an immediate local save by calling setCookies. Sessions that use the cookie repository actually process requests through DefaultSession.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
static create(identifier?: string): CookieRepository
Creates a cookie repository.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| identifier | string | No | Cookie repository ID. The value contains only uppercase letters, lowercase letters, and underscores. If undefined, null, or an empty string is passed, the value default is used. If any unallowed character is passed, error 1007900401 will be reported. Cookie repositories with the same ID share cookie information. (That is, cookie repository instances with the same ID are used as the same instance.) |
Returns:
| Type | Description |
|---|---|
| CookieRepository | Cookie repository instance. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900401 | Parameter error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
rcp.CookieRepository.create('myRepo');
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} setCookies(cookies: ResponseCookie | ResponseCookie[]): Promise<void>
Adds or modifies cookies, and persists existing cookies in the cookie repository to local storage. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| cookies | ResponseCookie | ResponseCookie[] | Yes | Cookie to be passed to the cookie repository. For a cookie, the following information will be recorded for it in the cookie repository: domain, httpOnly, path, isSecure, expires, name, and value. Cookies are considered identical if they share the same name, domain, and path. The default value of path is '/'. If domain is not set or is set to an empty string, error 1007900401 will be reported. maxAge will be converted to expires for application. If both maxAge and expires are set, the expiration time specified by maxAge prevails. The value of the expires field must be a GMT time string that complies with the RFC 7231 standard, for example, Wed, 21 Oct 2025 07:28:00 GMT. If the expires field is set to an invalid string, error 1007900401 will be reported. The system clears cookies that have expired from time to time. If an empty array is passed, only the existing cookies in the cookie repository are stored locally. |
Returns:
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900401 | Parameter error. |
| 1007900999 | Internal Error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
let cookieRepository = rcp.CookieRepository.create('myRepo');
let cookie: rcp.ResponseCookie = {
name:'session_1',
value:'10001',
domain:'www.example.com', // Set the domain name based on your needs.
maxAge: 60,
isSecure: true
}
cookieRepository.setCookies(cookie).then(() => {
console.info('Succeeded in setting cookies.');
}).catch((err: BusinessError) => {
console.error(`setCookies error, error code is ${err.code}, error data is ${err.data}`);
}) getAllCookies(): Promise<ResponseCookie[]>
Queries all cookies in the cookie repository. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Returns:
| Type | Description |
|---|---|
| Promise<ResponseCookie[]> | Promise used to return the ResponseCookie list. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900999 | Internal Error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
let cookieRepository = rcp.CookieRepository.create('myRepo');
cookieRepository.getAllCookies().then((cookies) => {
console.info(`Succeeded in getting all cookies, cookies num: ${cookies.length}`);
}).catch((err: BusinessError) => {
console.error(`getAllCookies error, error code is ${err.code}, error data is ${err.data}`);
}) getCookiesByUrl(url: URL): Promise<ResponseCookie[]>
Obtains cookies from the cookie repository based on the passed URL. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URL | Yes | HTTP request URL, which is used to match cookies. The matching rules are subject to the RFC 6265 standard. |
Returns:
| Type | Description |
|---|---|
| Promise<ResponseCookie[]> | Promise used to return the list of cookies matching the URL. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900999 | Internal Error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { url } from '@kit.ArkTS';
let cookieRepository = rcp.CookieRepository.create('myRepo');
cookieRepository.getCookiesByUrl(url.URL.parseURL('https://www.example.com')).then((cookies) => {
console.info(`Succeeded in getting cookies by URL, cookies num: ${cookies.length}`);
}).catch((err: BusinessError) => {
console.error(`getCookiesByUrl error, error code is ${err.code}, error data is ${err.data}`);
}) deleteCookies(cookies?: ResponseCookie | ResponseCookie[]): Promise<void>
Deletes specified cookies. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| cookies | ResponseCookie | ResponseCookie[] | No | Cookies to be deleted. For details about the cookie matching rules and error reporting rules, please refer to setCookies. |
Returns:
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900401 | Parameter error. |
| 1007900999 | Internal Error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
let cookieRepository = rcp.CookieRepository.create('myRepo');
let cookie: rcp.ResponseCookie = {
name:'session_1',
value:'10001',
domain:'www.example.com', // Set the domain name based on your needs.
maxAge: 60,
isSecure: true
}
cookieRepository.deleteCookies(cookie).then(() => {
console.info('Succeeded in deleting cookies.');
}).catch((err: BusinessError) => {
console.error(`deleteCookies error, error code is ${err.code}, error data is ${err.data}`);
}) deleteCookiesByUrl(url: URL): Promise<void>
Deletes cookies from the cookie repository based on the passed URL. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URL | Yes | HTTP request URL, which is used to match cookies. The matching rules are subject to the RFC 6265 standard. |
Returns:
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900999 | Internal Error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { url } from '@kit.ArkTS';
let cookieRepository = rcp.CookieRepository.create('myRepo');
cookieRepository.deleteCookiesByUrl(url.URL.parseURL('https://www.example.com')).then(() => {
console.info('Succeeded in deleting cookies by URL.');
}).catch((err: BusinessError) => {
console.error(`deleteCookiesByUrl error, error code is ${err.code}, error data is ${err.data}`);
}) get identifier(): string
Obtains the cookie repository ID.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Returns:
| Type | Description |
|---|---|
| string | Cookie repository ID. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
let cookieRepository = rcp.CookieRepository.create('myRepo');
let identifier = cookieRepository.identifier;
console.info(`identifier is: ${identifier}`); type SessionPathPreference = 'auto' | 'cellular-if-could' | 'mptcp'
Session path preferences.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 26.0.0
| Type | Description |
|---|---|
| 'auto' | No session path preference is configured, and the system automatically selects a path. |
| 'cellular-if-could' | The cellular network is preferred when it is available. This setting takes effect only when the ohos.permission.GET_NETWORK_INFO permission is enabled. For details about how to activate the cellular network, please refer to Network Connection Management. |
| 'mptcp' | The Multipath Transmission Control Protocol (MPTCP) is used. For details, please refer to RFC 8684. |
Defines data transmission settings for HTTP requests in a session, including automatic redirection and timeout settings.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| autoRedirect | boolean | No | Yes | Indicates whether to enable automatic redirection for HTTP requests. The options are true (yes) and false (no). The default value is true. |
| maxAutoRedirects | number | No | Yes | Maximum number of redirections. This parameter takes effect only when autoRedirect is set to true. Value range: [1, 2147483647] Default value: 50 Since: 5.0.0(12) |
| timeout | Timeout | No | Yes | HTTP request timeout settings for connection and data transmission. If this parameter is not set, the default value is used. |
| assumesHTTP3Capable | boolean | No | Yes | Indicates whether to attempt to upgrade the request to HTTP/3. The value true indicates that the system attempts to upgrade the request to HTTP/3 based on factors such as the client/server platform capability and network quality. The value false indicates that the request is not upgraded. The default value is false. To specify the HTTP version, use httpVersionSelectCallback. |
| pathPreference | PathPreference | No | Yes | Request path preferences. The configuration is only for system reference and the final path is determined by the device system. The options are 'auto' and 'cellular'. The default value is 'auto'. |
| serviceType | ServiceType | No | Yes | Service type. The default value is undefined. |
| pausePolicy | PausePolicy | No | Yes | Request suspension policy. Since: 5.0.0(12) |
| tcp | TcpConfiguration | No | Yes | TCP connection settings. Since: 6.0.0(20) |
| connectionReusePolicy | ConnectionReusePolicy | No | Yes | HTTP connection reuse mode. The default value is 'naive'. Since: 6.1.0(23) |
| throwErrorWhenEnableCellularFailed | boolean | No | Yes | Indicates whether to report an error code when pathPreference is set to 'cellular' and the cellular network fails to be enabled. The value true indicates that error code 1007900986 will be reported if the cellular network fails to be enabled. The value false indicates that no error code will be reported and another available network (such as Wi-Fi) will be used to send the request. The default value is false. Since: 6.1.1(24) |
| httpVersionSelectCallback | HttpVersionSelectCallback | No | Yes | Callback function for selecting the HTTP version, which returns HttpVersion. Since: 26.0.0 |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const transferConfig: rcp.TransferConfiguration = {
autoRedirect: true,
timeout: {
connectMs: 5000,
transferMs: 10000
},
assumesHTTP3Capable: true,
pathPreference: 'cellular',
connectionReusePolicy: 'balanced',
httpVersionSelectCallback: (url: rcp.URL): rcp.HttpVersion => {
return '2';
},
};
// Create a session using the configuration.
const session = rcp.createSession({ requestConfiguration: { transfer: transferConfig } }); Defines tracing settings for HTTP requests in a session, so you can collect information that can be used for data stream tracing, debugging, and performance analysis.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| verbose | boolean | No | Yes | Indicates whether to enable tracing to collect HTTP request/response stream details. The options are true (yes) and false (no). The default value is false. |
| infoToCollect | InfoToCollect | No | Yes | Events to be collected. By default, no event needs to be collected. |
| collectTimeInfo | boolean | No | Yes | Indicates whether to collect time-related information. The options are true (yes) and false (no). The default value is false. |
| httpEventsHandler | HttpEventsHandler | No | Yes | Callback triggered for specific operations during HTTP request/response processing. The default value is undefined. |
| plaintextInException | boolean | No | Yes | Indicates whether to display plaintext content in the exception description when an exception is reported. The options are true and false. The default value is false. Since: 26.0.0 |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
// Define a custom response handler.
const customHttpEventsHandler: rcp.HttpEventsHandler = {
onDataReceive: (incomingData: ArrayBuffer) => {
// Custom logic for processing incoming data.
console.info(`Received data length: ${incomingData.byteLength}`);
return incomingData.byteLength;
},
onUploadProgress: (totalSize: number, transferredSize: number) => {
// Custom logic for processing the upload progress.
console.info(`Upload progress: ${transferredSize} of ${totalSize}`);
},
onDownloadProgress: (totalSize: number, transferredSize: number) => {
// Custom logic for processing the download progress.
console.info(`Download progress: ${transferredSize} of ${totalSize}`);
},
onHeaderReceive: (headers: rcp.ResponseHeaders) => {
// Custom logic for processing response headers.
console.info(`Received headers: ${JSON.stringify(headers)}`);
},
onDataEnd: () => {
// Custom logic for processing the completion of data transmission.
console.info('Data transfer complete');
},
onCanceled: () => {
// Custom logic for processing the cancel operation.
console.info('Request/response canceled');
},
onStatusCodeReceive: (statusCode: number, request?: rcp.Request) => {
// Custom logic for processing the status code.
console.info(`Received statusCode: ${statusCode}`);
}
};
// Configure tracing settings.
const tracingConfig: rcp.TracingConfiguration = {
verbose: true,
infoToCollect: {
textual: true,
incomingHeader: true,
outgoingHeader: true,
incomingData: true,
outgoingData: true,
incomingSslData: true,
outgoingSslData: true
},
collectTimeInfo: true,
httpEventsHandler: customHttpEventsHandler
};
// Create a session using the configuration.
const session = rcp.createSession({requestConfiguration: {tracing: tracingConfig}});
console.info(`session id: ${session.id}`); type ProxyConfiguration = 'system' | 'no-proxy' | WebProxy
Defines proxy settings for HTTP requests in a session, so you can flexibly choose between the options of system proxy, custom proxy, and no proxy.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'system' | HTTP proxy settings. 'system': The system proxy configuration is used. |
| 'no-proxy' | HTTP proxy settings. 'no-proxy': No proxy is used. |
| WebProxy | HTTP proxy settings. WebProxy: The custom proxy configuration is used. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
// Configure the system proxy (default).
const systemProxyConfig = 'system';
// Configure the custom proxy.
const customProxyConfig: rcp.WebProxy = {
url: 'http://custom-proxy.example.com',
createTunnel: 'always',
exclusions: ['http://exclude.example.com'],
security: {
certificate: {
content: '-----BEGIN CERTIFICATE-----\n...',
type: 'PEM',
key: '-----BEGIN PRIVATE KEY-----\n...', // Set the key based on your service needs.
keyPassword: 'your-password'
},
serverAuthentication: {
credential: {
username: 'proxy-username',
password: 'proxy-password'
},
authenticationType: 'basic'
}
}
};
// Configure the non-proxy mode.
const noProxyConfig = 'no-proxy';
// Use the proxy configuration during session creation.
const sessionWithSystemProxy = rcp.createSession({ requestConfiguration: { proxy: systemProxyConfig } });
console.info(`sessionWithSystemProxy id: ${sessionWithSystemProxy.id}`);
const sessionWithCustomProxy = rcp.createSession({ requestConfiguration: { proxy: customProxyConfig } });
console.info(`sessionWithCustomProxy id: ${sessionWithCustomProxy.id}`);
const sessionWithNoProxy = rcp.createSession({ requestConfiguration: { proxy: noProxyConfig } });
console.info(`sessionWithNoProxy id: ${sessionWithNoProxy.id}`); Defines DNS settings for HTTP requests in a session. You can configure DNS rules flexibly, including customizing the DNS server or static DNS rules.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| dnsRules | DnsServers | StaticDnsRules | DynamicDnsRule | No | Yes | DNS rule. The default value is undefined. Other options are as follows: DnsServers: A specified DNS server is preferentially used to resolve the host name. StaticDnsRules: If the host name is matched, a specified address is used preferentially. DynamicDnsRule: The address returned in the function is used preferentially. Note: If multiple static or dynamic DNS rules are configured for the same domain name, only the last IP address takes effect by default. Since version 6.0.0(20), you can make multiple IP addresses effective at the same time by setting happyEyeballOnDnsRule to true. |
| dnsOverHttps | DnsOverHttpsConfiguration | No | Yes | DNS over HTTPS. The default value is undefined. If this parameter is set, DNS-resolved addresses will be used by priority. |
| happyEyeballOnDnsRule | boolean | No | Yes | Indicates whether to enable Happy Eyeballs connection racing. When the network path to a specific address or address family (IPv4 or IPv6) is blocked, unreachable, or suffers from poor network quality, the Happy Eyeballs connection racing mechanism helps establish a connection more quickly. The options are as follows: true: Enable Happy Eyeballs connection racing when DNS rules are configured (defined by the dnsRules parameters). false: Disable Happy Eyeballs connection racing when DNS rules are configured (defined by the dnsRules parameters). The default value is false. Since: 6.0.0(20) Note: This parameter takes effect only when dnsRules is set. If dnsRules is not set, the Happy Eyeballs connection racing is enabled by default and cannot be disabled. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
// Configure a custom DNS server. The following IP address is for reference only.
const customDnsServers: rcp.DnsServers = [
{ ip: '192.168.1.1' },
{ ip: '192.168.1.2', port: 53 }
];
// Configure a static DNS rule. The following IP address is for reference only.
const staticDnsRules: rcp.StaticDnsRules = [
{ host: 'example.com', port: 80, ipAddresses: ['192.168.1.1', '192.168.1.2'] },
{ host: 'sub.example.com', port: 443, ipAddresses: ['192.168.2.1'] }
];
// Configure DNS over HTTPS.
const dohConfig: rcp.DnsOverHttpsConfiguration = {
url: 'https://dns.example.com/dns-query',
skipCertificatesValidation: true
};
// Use the DNS configuration during session creation.
const sessionWithCustomDns = rcp.createSession({ requestConfiguration: { dns: { dnsRules: customDnsServers } } });
const sessionWithStaticDns = rcp.createSession({
requestConfiguration: {
dns: {
// For example, '192.168.1.2' is valid for example.com.
// For sub.example.com, '192.168.2.1' is valid.
dnsRules: staticDnsRules,
}
}
});
const sessionWithDoh = rcp.createSession({ requestConfiguration: { dns: { dnsOverHttps: dohConfig } } });
// If DNS rules are set during session creation, enable happyEyeballOnDnsRule.
const sessionWithStaticDnsRulesAndHappyEyeball = rcp.createSession({
requestConfiguration: {
dns: {
dnsRules: staticDnsRules, // Set DNS rules here.
happyEyeballOnDnsRule: true, // Enable happyEyeballOnDnsRule here.
}
}
});
// Enable happyEyeballOnDnsRule in the request configuration when setting DNS rules.
const request = new rcp.Request('https://example.com');
request.configuration = {
dns: {
dnsRules: staticDnsRules, // Set DNS rules here.
happyEyeballOnDnsRule: true, // Enable happyEyeballOnDnsRule here.
}
}; Defines DNS over HTTPS settings, allowing for secure DNS resolution via HTTPS endpoints.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| url | URLOrString | No | No | URL or string used to specify the DoH endpoint. |
| skipCertificatesValidation | boolean | No | Yes | Indicates whether to skip SSL/TLS certificate verification for a DoH endpoint. The options are true (yes) and false (no). The default value is false. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
// Configure DNS over HTTPS settings.
const dohConfig: rcp.DnsOverHttpsConfiguration = {
url: 'https://dns.example.com/dns-query',
skipCertificatesValidation: true
};
// Use the DNS over HTTPS settings during session creation.
const sessionWithDoh = rcp.createSession({ requestConfiguration: { dns: { dnsOverHttps: dohConfig } } }); Defines security-related settings for a session, including certificate and server identity verification settings.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| remoteValidation | 'system' | 'skip' | CertificateAuthority | ValidationCallback | No | Yes | Certificate authority (CA), which is used to verify the identity of a remote server. The default value is 'system'. If the parameter is not set, the default value is used. The options are as follows: 'system' (default): The system CA is used. 'skip': Verification is skipped. CertificateAuthority: The specific CA is used. ValidationCallback: The certificate verification is customized. Note: In 5.0.0(12) and later versions, the option ValidationCallback is also supported. |
| certificate | ClientCertificate | No | Yes | Client certificate, which will be sent to the remote server to verify the identity of the client. The default value is undefined, indicating that verification is not required. |
| certificateEnc | ClientCertificate | No | Yes | Client certificate, which is sent to the remote TLCP server to verify the client identity. This parameter takes effect only when securityLayerType is set to 'tlcp'. The default value is undefined, indicating that the server does not need to verify the client certificate. Since: 26.0.0 |
| tlsOptions | 'system' | CipherSuite[] | TlsV13Option | TlsV12Option| TlsV11Option | TlsV10Option | No | Yes | TLS version selector. The options are as follows: 'system' (default): TLS version used by the system CipherSuite[]: array used to declare the cipher suite types TlsV13Option: TLS 1.3 TlsV12Option: TLS 1.2 TlsV11Option: TLS 1.1 TlsV10Option: TLS 1.0 Since: 5.0.0(12) |
| tlsRange | TlsVersionRangeOptions | No | Yes | TLS version range configurator, which can be used to define the TLS version range that can be used by the client. By default, this attribute is not set. Since: 6.0.0(20) |
| serverAuthentication | ServerAuthentication | No | Yes | Indicates whether to verify the server identity during a secure connection. The identity is not verified by default. |
| certificatePinning | CertificatePinning| CertificatePinning[] | No | Yes | Certificate pinning settings. Since: 5.0.0(12) |
| challenge | OnAuthenticationChallenge | No | Yes | Custom authentication challenge. Since: 6.1.0(23) |
| securityLayerType | SecurityLayerType | No | Yes | Security-layer protocol type. The default value is 'ssl-tls'. If this parameter is set to 'tlcp', the following restrictions apply: 1. The Emulator is not supported. When the 'tlcp' type is used to initiate a request on the Emulator, error 804 will be reported. 2. The server cannot function as a proxy server. If security.securityLayerType of WebProxy is set to 'tlcp', error 1007900401 will be reported when a request is initiated. 3. remoteValidation can only be set to 'skip', CertificateAuthority, or ValidationCallback. When this parameter is set to CertificateAuthority, only filePath can be passed. In other cases, error 1007900401 will be reported during the request. 4. content cannot be passed in certificate and certificateEnc. Otherwise, error 1007900401 will be reported during the request. 5. The type parameter of certificate and certificateEnc can only be set to 'PEM'. Otherwise, error 1007900401 will be reported during the request. 6. tlsOptions, tlsRange, and certificatePinning are not supported. Otherwise, error 1007900401 will be reported during the request. Since: 26.0.0 |
| certificateDecompress | CertificateDecompress| CertificateDecompress[] | No | Yes | TLS 1.3 extension protocol certificate decompression configuration. You are advised to set tlsOptions in SecurityConfiguration to TlsV13Option. This configuration takes effect only for phones. Since: 26.0.0 |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
// Configure security settings.
const securityConfig: rcp.SecurityConfiguration = {
remoteValidation: 'system',
certificate: {
content: '-----BEGIN CERTIFICATE-----\n...',
type: 'PEM',
key: '-----BEGIN PRIVATE KEY-----\n...', // Set the key based on your service needs.
keyPassword: 'your-password'
},
serverAuthentication: {
credential: {
username: 'exampleUser',
password: 'examplePassword'
},
authenticationType: 'basic'
},
tlsOptions: {
tlsVersion: 'TlsV1.3',
},
certificateDecompress: 'zlib',
};
// Use the security settings during session creation.
const sessionWithSecurityConfig = rcp.createSession({ requestConfiguration: { security: securityConfig } }); CA used to verify the identity of a remote server.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| content | string | ArrayBuffer | No | Yes | A bundle of CA certificates for peer verification, in PEM format. |
| filePath | string | No | Yes | CA certificate path for peer verification. The certificate file must be in PEM format. |
| folderPath | string | No | Yes | Path to the directory storing multiple CA certificates used for peer verification. Files in this directory must be in PEM format. |
Client certificate.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| content | string | ArrayBuffer | No | Yes | Content of the certificate issued by the CA. It is either a string or ArrayBuffer. |
| filePath | string | No | Yes | Path of the certificate file, which includes the CA that issues the certificate. The default value is undefined. |
| type | 'PEM' | 'DER' | 'P12' | No | Yes | Encoding format of the client certificate. The default value is undefined. |
| key | string | No | Yes | Path of the private key file of the client certificate. The default value is undefined. |
| keyPassword | string | No | Yes | Password of the client certificate. The default value is undefined. |
Defines HTTP server identity verification information.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| credential | Credential | No | No | Server credential. The default value is undefined. |
| authenticationType | AuthenticationType | No | Yes | Server identity verification type. If the type is not set, negotiation with the server is required. |
Sets the available TLS version range. You can define the minimum and maximum bounds of supported TLS versions for security purposes, and specify the list of cipher suites available within the range. If the minimum version is later than the maximum version, the error 401 will be reported when a request is initiated.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| min | TlsVersion | No | Yes | Minimum TLS version. By default, the system automatically selects a value and the parameter does not need to be set. |
| max | TlsVersion | No | Yes | Maximum TLS version. By default, the system automatically selects a value and the parameter does not need to be set. |
| cipherSuite | CipherSuite[] | No | Yes | List of cipher suites available within the TLS version range. By default, the system automatically specifies the range and the parameter does not need to be set. |
type OnAuthenticationChallenge = (info: AuthenticationChallengeInfo[], response: Response, challengeCount: number) => ServerAuthentication | null
Authentication challenge callback function. You can use this callback function to process the authentication challenge. This callback function is called when the HTTP response status code is 401.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| info | AuthenticationChallengeInfo[] | Yes | Authentication challenge information. The system parses the WWW-Authenticate information in the response header and converts the information into key-value pairs. |
| response | Response | Yes | HTTP response of the current authentication challenge. |
| challengeCount | number | Yes | Number of authentication challenges. If a challenge is not validated by the server, another authentication challenge may be triggered. The system does not limit the number of challenges. |
Returns:
| Type | Description |
|---|---|
| ServerAuthentication | null | Authentication information of the HTTP server or a null value. If authentication information is returned, the system uses the information provided by a user to perform the authentication challenge. If null is returned, the challenge is canceled. |
type SecurityLayerType = 'ssl-tls' | 'tlcp'
Security-layer protocol type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 26.0.0
| Type | Description |
|---|---|
| 'ssl-tls' | Indicates that the TLS protocol is used at the security layer. |
| 'tlcp' | Indicates that the TLCP protocol is used at the security layer. |
type CertificateDecompress = 'zlib' | 'brotli'
Certificate decompression algorithm. For details, please refer to RFC 8879.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 26.0.0
| Type | Description |
|---|---|
| 'zlib' | The zlib algorithm is used for decompression. |
| 'brotli' | The brotli algorithm is used for decompression. |
type AuthenticationChallengeInfo = Record<string, string>
Defines authentication challenge information returned by the server.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
| Type | Description |
|---|---|
| Record<string, string> | Authentication challenge information parsed from WWW-Authenticate. Common keys include type and realm. |
Defines an HTTP request.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| id | string | Yes | No | Unique request object ID, which is generated by the system. |
| url | URL | No | No | Pointer to the HTTP request URL. |
| method | HttpMethod | No | No | HTTP method. The default value is 'GET'. |
| headers | RequestHeaders | No | Yes | HTTP request header. The default value is undefined. |
| content | RequestContent | No | Yes | HTTP request content. The default value is undefined. |
| cookies | RequestCookies | No | Yes | HTTP request cookies. This configuration will be converted into the HTTP Cookies header. The default value is undefined. |
| transferRange | TransferRange | TransferRange[] | No | Yes | HTTP transmission range. This configuration will be converted into the HTTP Range header. An HTTP request with the Range header requires the server to return only a part of the HTTP response. The default value is undefined. |
| configuration | Configuration | No | Yes | HTTP request configuration, which will be used to replace the default or session-range configuration. The default value is undefined. |
| destination | ResponseBodyDestination | No | Yes | Destination of the HTTP response body. Since: 5.0.0(12) |
| cacheControl | CacheControl | No | Yes | HTTP request cache settings. If this attribute is set, the cache settings in SessionConfiguration do not take effect. The default value is undefined. Since: 6.0.0(20) |
| connectOnly | boolean | No | Yes | Indicates whether a request is used only for establishing a connection. The options are true (yes) and false (no). If this parameter is set to false, the request can be used to transmit data. The default value is false. Since: 6.1.1(24) |
constructor(url: URLOrString, method?: HttpMethod, headers?: RequestHeaders, content?: RequestContent, cookies?: RequestCookies, transferRange?: TransferRange | TransferRange[], configuration?: Configuration)
Provides the constructor used to create a Request object.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | Request address type. In a constructor, a character string that represents a URL needs to be converted into a URL. |
| method | HttpMethod | No | HTTP request method. The default value is GET. |
| headers | RequestHeaders | No | HTTP request header. The default value is undefined. |
| content | RequestContent | No | HTTP request body. The default value is undefined. |
| cookies | RequestCookies | No | HTTP request cookies. This configuration will be converted into the HTTP Cookies header. |
| transferRange | TransferRange| TransferRange[] | No | HTTP transmission range. This configuration will be converted into the HTTP Range header. |
| configuration | Configuration | No | HTTP request configuration. For details, please refer to Configuration. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
let headers: rcp.RequestHeaders = {
'accept': 'application/json'
};
let content = 'data to send';
let configuration: rcp.Configuration = {
transfer: {
timeout: { connectMs: 60000, transferMs: 60000 }
}
};
let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
let transferRange: rcp.TransferRange = { from: 100, to: 200 };
let req = new rcp.Request('http://example.com', 'POST', headers, content, cookies, transferRange, configuration); type URL = url.URL
Request address type, which links to URL in @ohos.url.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| url.URL | @ohos.url.URL type, indicating the request URL type. The value can be any value of this type. |
type X509Cert = cert.X509Cert
x509 certificate type, which links to X509Cert in @ohos.security.cert.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| cert.X509Cert | @ohos.security.cert.X509Cert type. The value can be any value of this type. |
type File = fs.File
File in the file system, which links to File in @ohos.file.fs.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| fs.File | @ohos.file.fs.File type. The value can be any value of this type. |
type RandomAccessFile = fs.RandomAccessFile
File that can be accessed randomly, which links to RandomAccessFile in @ohos.file.fs.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| fs.RandomAccessFile | @ohos.file.fs.RandomAccessFile type. The value can be any value of this type. |
type Stream = fs.Stream
Data stream type, which links to Stream in @ohos.file.fs.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| fs.Stream | @ohos.file.fs.Stream type. The value can be any value of this type. |
type RawDataContent = string | ArrayBuffer | object
Defines basic data types of ArkTs.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| string | Text string, which can be any value of this type. |
| ArrayBuffer | Binary data, which can be any value of this type. |
| object | Object, which can be any value of this type. |
type FileDescriptor = number
Descriptor of a file, which is an abstract representation for accessing a file or I/O device.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| number | Number type. The value can be any number. |
type LocalFile = FileDescriptor | File | RandomAccessFile
A file-like object that enables users to interact with it using various file descriptors or file objects.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| FileDescriptor | Descriptor of a file, which is an integer that identifies an open file. |
| File | A file in a file system, which can be used to obtain the file descriptor, path, and name, as well as to perform locking and unlocking operations on the file. |
| RandomAccessFile | Type for implementing random access to files, including operations such as reading file descriptors and file pointers, setting file pointers, and writing files. |
Provides the function of writing data to a file.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
write(buffer: ArrayBuffer): Promise<void | number>
Writes data to a file. This API uses a promise to return the result asynchronously.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | Data to be written to a file. |
Returns:
| Type | Description |
|---|---|
| Promise<void | number> | Promise object. No result is returned, or the number of written bytes is returned. |
Provides the function for reading data from a file.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
read(buffer: ArrayBuffer): Promise<number>
Reads data from a file.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | File from which data needs to be read. |
Returns:
| Type | Description |
|---|---|
| Promise<number> | This API uses a promise to return the number of bytes read. |
Provides the function of writing data to a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
write(buffer: ArrayBuffer): Promise<void | number>
Writes data from a file to a data stream. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | Buffer for storing the read data. |
Returns:
| Type | Description |
|---|---|
| Promise<void | number> | Promise object. No result is returned, or the number of written bytes is returned. |
Provides the function of synchronously writing data to a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
writeSync(buffer: ArrayBuffer): void | number
Writes data to a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | Buffer for storing the read data. |
Returns:
| Type | Description |
|---|---|
| void | number | No value is returned, or the number of written bytes is returned. |
Provides the function of reading data from a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
read(buffer: ArrayBuffer): Promise<number>
Reads data from a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | Buffer for storing the read data. |
Returns:
| Type | Description |
|---|---|
| Promise<number> | This API uses a promise to return the number of bytes read. |
Provides the function of synchronously reading data from a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
readSync(buffer: ArrayBuffer): number
Reads data from a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | Buffer for storing the read data. |
Returns:
| Type | Description |
|---|---|
| number | Number of bytes read. |
Downloads data to the path specified when the request is initiated through DownloadToFile.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| path | Path | No | No | If Request.destination specifies that content needs to be downloaded to a file, path indicates the path for storing the file. |
| requestSkipped | true | No | Yes | Indicates whether to skip the request. If this parameter is set to true, the request is skipped. If this parameter is not set, the request is not skipped. |
Saves data to either a specified directory or the default directory.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| path | Path | No | No | Target path for data download. |
| skipRequest | boolean | No | Yes | Indicates whether to skip the request. The value true indicates yes and the value false indicates no. The default value is false. |
type TargetFileCallback = (request: Request, suggestedPath: Path) => TargetFile | Promise<TargetFile>
Callback function that returns a TargetFile object asynchronously using a promise.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
Returns:
| Type | Description |
|---|---|
| TargetFile | Promise<TargetFile> | Callback used to return the TargetFile object, or promise used to return the TargetFile object, which indicates the location for storing the downloaded data. |
type IncomingDataCallback = (incomingData: ArrayBuffer) => void | Promise<void>
Callback function for processing downloaded data. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| incomingData | ArrayBuffer | Yes | ArrayBuffer data to be processed. |
Returns:
| Type | Description |
|---|---|
| void | Promise<void> | Callback that returns no value, or promise that returns no result. |
Uploads a file from the client to the server.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| fileOrPath | Path | LocalFile | ReadFile | Yes | No | File to be uploaded or the path of the file to be uploaded. For details, please refer to Application Files. |
constructor(fileOrPath: Path | LocalFile | ReadFile)
Provides the constructor used to create an UploadFromFile object.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| fileOrPath | Path | LocalFile | ReadFile | Yes | File to be uploaded or the path of the file to be uploaded. For details, please refer to Application Files. |
Uploads a file in stream mode.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| stream | Stream | ReadStream | SyncReadStream | Yes | No | Stream to be uploaded. |
constructor(stream: Stream | ReadStream | SyncReadStream)
Provides the constructor used to create an UploadFromStream object.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| stream | Stream | ReadStream | SyncReadStream | Yes | Stream to be uploaded. |
type DownloadToFile = { kind: 'file'; file: TargetFileCallback; } | { kind: 'file'; file: Path; keepLocal?: boolean; } | { kind: 'file'; file: LocalFile | WriteFile; } | { kind: 'folder'; path: Path; keepLocal?: boolean; }
Downloads a file to a specified directory or file. If a file is downloaded to a directory, its name on the server will be retained. The value contains all types in the following table. The kind option is used to specify whether the data will be downloaded to a file or a directory, and the file parameter specifies the target file or directory for the download. For details, please refer to Application Files.
The value contains all types in the following table.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| { kind: 'file'; file: TargetFileCallback; } | Returns the download result through a callback. The value of the key kind is 'file' and the value of the key file is TargetFileCallback. |
| { kind: 'file'; file: Path; keepLocal?: boolean; } | Downloads data to a specified path. The value of the key kind is 'file' and the value of the key file is the target path. keepLocal indicates whether to retain the local file with the same name. The options are true (yes) and false (no). The default value is false. |
| { kind: 'file'; file: LocalFile | WriteFile; } | Downloads data to a specified file. The value of the key kind is 'file' and the value of the key file is LocalFile or WriteFile. |
| { kind: 'folder'; path: Path; keepLocal?: boolean; } | Downloads data to a specified folder. The value of the key kind is 'folder' and the value of the key path is the target path. keepLocal indicates whether to retain the local file with the same name. The options are true (yes) and false (no). The default value is false. |
type DownloadToStream = { kind: 'stream'; stream: Stream | WriteStream | SyncWriteStream; }
Downloads a file to a data stream.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| { kind: 'stream'; stream: Stream| WriteStream| SyncWriteStream } | The value of the key kind is 'stream' and the value of the key stream is: Stream, WriteStream, or SyncWriteStream object |
Defines the request suspension policy.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| receiving | ReceivingPausePolicy | No | Yes | Policy for suspending response body reception. |
| sending | SendingPausePolicy | No | Yes | Policy for suspending request body sending. |
Defines the policy for suspending request reception by timeout.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'timeout' | No | No | Policy for suspending request reception by timeout. |
| timeoutMs | number | No | No | Timeout interval, If the framework does not receive data from the server within the timeout interval, requests are suspended. Unit: millisecond Value range: [1, 1000] Default value: 0 |
Defines the policy for suspending request reception by cached data size.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'cacheSize' | No | No | Policy for suspending request reception by cached data size. |
| size | number | No | No | Maximum cached data size. If the cached data size reaches this value, requests are suspended. Value range: [0, 1048576] |
type ReceivingPausePolicy = ReceivingPauseByCache | ReceivingPauseByTimeout
Defines the policy for suspending request reception.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| ReceivingPauseByCache | Maximum cache size of the suspension policy. |
| ReceivingPauseByTimeout | Timeout interval of the suspension policy. |
const NetworkOutputQueue: NetworkOutputQueueConstructor
Call new NetworkInputQueue() to create an INetworkOutputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
NetworkOutputQueueConstructor is a constructor of INetworkOutputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
new (): INetworkOutputQueue
Creates an INetworkOutputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Returns:
| Type | Description |
|---|---|
| INetworkOutputQueue | Synchronous read queue object. |
new (maxSize: number): INetworkOutputQueue
Creates an INetworkOutputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| maxSize | number | Yes | Queue size, which indicates the maximum number of bytes that can be written. |
Returns:
| Type | Description |
|---|---|
| INetworkOutputQueue | Synchronous read queue object. |
new (maxSize: number, pausePolicyOverride: ReceivingPausePolicy): INetworkOutputQueue
Creates an INetworkOutputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| maxSize | number | Yes | Queue size, which indicates the maximum number of bytes that can be written. |
| pausePolicyOverride | ReceivingPausePolicy | Yes | Policy for suspending request reception. |
Returns:
| Type | Description |
|---|---|
| INetworkOutputQueue | Synchronous read queue object. |
Defines a read queue for synchronously reading response bodies, which is constructed using new NetworkOutputQueue().
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
read(maxBytesToRead: number): ArrayBuffer
Reads a data segment from a queue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| maxBytesToRead | number | Yes | Maximum number of bytes that can be read from the queue. |
Returns:
| Type | Description |
|---|---|
| ArrayBuffer | Binary data that is read. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900990 | Out of memory. |
readInto(buffer: ArrayBuffer): number
Reads data from the queue and stores the data in the specified buffer.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | ArrayBuffer | Yes | Buffer to which data is read. |
Returns:
| Type | Description |
|---|---|
| number | Number of bytes in the read binary data. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900990 | Out of memory. |
getStoredBytes(): number
Obtains the size of data in the queue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Returns:
| Type | Description |
|---|---|
| number | Obtains the size of data in the queue, in bytes. |
type ResponseBodyDestination = 'array-buffer'| IncomingDataCallback | DownloadToFile | DownloadToStream | INetworkOutputQueue
Sets the destination of a response, so the HTTP client can send response data to the destination.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| 'array-buffer' | Data of the ArrayBuffer type. By default, the response body is written to the memory. |
| IncomingDataCallback | Data of the IncomingDataCallback type. The response body is written to the callback function. |
| DownloadToFile | Data of the DownloadToFile type. The response body is written to a file. |
| DownloadToStream | Data of the DownloadToStream type. The response body is written to a custom stream. |
| INetworkOutputQueue | Data of the INetworkOutputQueue type. The response body is written to the queue. |
type URLOrString = URL | string
Union set of URL objects or strings representing URLs. It can be used as an input parameter of the HTTP/HTTPS address.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| URL | URL object, which can be used as an input parameter of the HTTP/HTTPS address. |
| string | URL string, which can be used as an input parameter of the HTTP/HTTPS address. |
type PathPreference = 'auto' | 'cellular'
Makes settings about HTTP request path preferences. This setting is only for system reference and the final path is determined by the device system.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'auto' | The system selects a path automatically. |
| 'cellular' | The cellular network path is used. |
type ConnectionReusePolicy = 'balanced' | 'forbidden' | 'naive'
HTTP connection reuse mode.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
| Type | Description |
|---|---|
| 'balanced' | HTTP connections are used in a balanced manner. The system selects the HTTP connection with the lowest current load. |
| 'forbidden' | Connection reuse is forbidden. A new HTTP connection is created for each request. |
| 'naive' | Simple connection reuse is applied. The system selects the first available HTTP connection it finds. |
type HttpVersionSelectCallback = (url: URL) => HttpVersion
Callback function for selecting the HTTP version. This function is executed before a request is initiated. If the callback function does not return 'unknown', the returned HTTP version is used, and assumesHTTP3Capable does not take effect. If the client or server does not support the version specified by the developer, the request may be automatically downgraded to an earlier version or the request may fail.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 26.0.0
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URL | Yes | URL of the target resource in the HTTP request. |
Returns:
| Type | Description |
|---|---|
| HttpVersion | Selected HTTP version. |
type IpAddress = string
IP address type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| string | IP address of the string type, which can be an IPv4 or IPv6 address. |
type DnsServers = IpAndPort[]
Sets the custom DNS server in DnsConfiguration. It provides a flexible way to define a list of IP addresses and associated port numbers.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Defines IP addresses and mapping port numbers in scenarios where the pairs of IP addresses and port numbers need to be specified, such as DNS server customization in the DnsServers API.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| ip | IpAddress | No | No | IP address , which can be an IPv4 or IPv6 address. |
| port | number | No | Yes | Mapping port number. The value ranges from 0 to 65535. The default value is 53. |
type ServiceType = 'default' | 'background' | 'realtimeVoice' | 'realtimeVideo' | 'callSignaling' | 'realtimeGame' | 'normalGame' | 'shortVideo' | 'longVideo' | 'livestreamingAnchor' | 'livestreamingWatcher' | 'download' | 'upload' | 'browser'
Defines the network service type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'default' | Default service type. This type is suitable for most general service requirements. Note: All options except 'default' are new options in version 5.0.0(12). |
| 'background' | Background service type. This type is suitable for tasks running in the background, including scheduled tasks, background data synchronization, and notification push. |
| 'realtimeVoice' | Real-time voice service type. This type is suitable for real-time voice services such as voice call, video conference, and instant call. |
| 'realtimeVideo' | Real-time video service type. This type is suitable for real-time video services. |
| 'callSignaling' | Signaling service type. This type is suitable for transmitting and managing call signaling in calls, including call setup, disconnection, and transfer. |
| 'realtimeGame' | Real-time game service type. This type is suitable for real-time multi-player games that need to prioritize low latency and high reliability to ensure smooth and synchronized gameplay experiences for all players. |
| 'normalGame' | Common game service type. This type is suitable for non-real-time game services, such as single-player games, offline games, and non-battle games. |
| 'shortVideo' | Short video service type. This type is suitable for uploading, downloading, and playing short videos. |
| 'longVideo' | Long video service type. This type is suitable for long video services. |
| 'livestreamingAnchor' | Live TV playback control service type. This type is suitable for the streamer end of live streaming platforms. |
| 'livestreamingWatcher' | Live TV playback service type. This type is suitable for the viewer end of live streaming platforms. |
| 'download' | Download service type. This type is suitable for resource download services. |
| 'upload' | Upload service type. This type is suitable for resource upload services. |
| 'browser' | Browser service type. This type is suitable for web page loading and interaction in a browser. |
type HttpMethod = 'GET' | 'POST' | 'HEAD' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | (string & NonNullable<unknown>)
Represents various HTTP methods used in network requests. An HTTP method defines the operation to be performed on a specified resource.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'GET' | GET network request method. This method is used to obtain data such as web pages, images, and API data from the server. |
| 'POST' | POST network request method. This method is used to submit data such as forms and files to the server. |
| 'HEAD' | HEAD network request method. This method is similar to GET but only retrieves the header information of the resource without returning the resource body. It is usually used to check whether a resource exists and obtain the metadata of a resource. |
| 'PUT' | PUT network request method. This method is usually used to update existing resources on the server. |
| 'DELETE' | DELETE network request method. This method is usually used to delete existing resources on the server. |
| 'PATCH' | PATCH network request method. This method is usually used to partially update existing resources on the server. |
| 'OPTIONS' | OPTIONS network request method. This method is usually used to query the communication options of a target resource and is commonly used in cross-domain requests to determine the HTTP methods supported by the server. |
| (string & NonNullable<unknown>) | Option used to ensure that the value of the HttpMethod type is a non-empty string. |
type RequestHeaders = { [k: string]: string | string[] | undefined; 'authorization'?: string; 'accept'?: ContentType | ContentType[]; 'accept-charset'?: string | string[]; 'accept-encoding'?: ContentCoding | ContentCoding[]; 'accept-language'?: string | string[]; 'cache-control'?: string | string[]; 'cookie'?: string | string[]; 'range'?: string | string[]; 'upgrade'?: string | string[]; 'user-agent'?: string; 'content-type'?: ContentType; }
Defines the request header type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
{ [k: string]: string | string[] | undefined; 'authorization'?: string; 'accept'?: ContentType | ContentType[]; 'accept-charset'?: string | string[]; 'accept-encoding'?: ContentCoding | ContentCoding[]; 'accept-language'?: string | string[]; 'cache-control'?: string | string[]; 'cookie'?: string | string[]; 'range'?: string | string[]; 'upgrade'?: string | string[]; 'user-agent'?: string; 'content-type'?: ContentType; } | If the key is [k: string]: string | string[] | undefined, the value contains one or more key-value pairs. In a key-value pair, the key can be any string and the value can be a string, string array, or undefined. If the key is authorization, the value can be any string. If the key is 'accept', the value can be any value of the ContentType or ContentType type. If the key is 'accept-charset', the value can be any string or string array. If the key is 'accept-encoding', the value can be any value of the ContentCoding or ContentCoding type. If the key is 'accept-language', the value can be any string or string array. If the key is 'cache-control', the value can be any string or string array. If the key is 'cookie', the value can be any string or string array. If the key is 'range', the value can be any string or string array. If the key is 'upgrade', the value can be any string or string array. If the key is 'user-agent', the value can be any string. If the key is 'content-type', the value can be any value of the ContentType type. If this key does not exist or is set to an empty string, the system uses the default content type based on RequestContent. If you do not want to use the default content type, pass a single space. |
Defines the policy for suspending request sending.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'timeout' | No | No | Policy for suspending request sending. |
| timeoutMs | number | No | No | Timeout interval, in milliseconds. If the framework does not receive data from the app within the timeout interval, requests are suspended. Value range: [1, 1000] Default value: 0 |
const NetworkInputQueue: NetworkInputQueueConstructor
Calls new NetworkInputQueue() to create an INetworkInputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Constructs an INetworkInputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
new (): INetworkInputQueue
Creates an INetworkInputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Returns:
| Type | Description |
|---|---|
| INetworkInputQueue | Synchronous write queue object. |
new (maxSize: number): INetworkInputQueue
Creates an INetworkInputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| maxSize | number | Yes | Queue size, which indicates the maximum number of bytes that can be written. |
Returns:
| Type | Description |
|---|---|
| INetworkInputQueue | Synchronous write queue object. |
new (maxSize: number, pausePolicyOverride: SendingPausePolicy): INetworkInputQueue
Creates an INetworkInputQueue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| maxSize | number | Yes | Queue size, which indicates the maximum number of bytes that can be written. |
| pausePolicyOverride | SendingPausePolicy | Yes | Policy for suspending request sending. |
Returns:
| Type | Description |
|---|---|
| INetworkInputQueue | Synchronous write queue object. |
Defines a write queue for synchronously writing request bodies, which is constructed using new NetworkInputQueue().
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
write(buffer: string | ArrayBuffer): void
Writes a data segment to the queue, which will be sent by an I/O thread of the framework at a proper time.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| buffer | string | ArrayBuffer | Yes | Data to be sent. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900990 | Out of memory. |
close(): void
Closes the synchronous write queue. Then an I/O thread no longer reads data from the queue.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
getFreeSpace(): number
Obtains the remaining writable space.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Returns:
| Type | Description |
|---|---|
| number | Obtains the remaining writable space. |
type RequestContent = RawDataContent | Form | MultipartForm | GetDataCallback | UploadFromFile | UploadFromStream | INetworkInputQueue
Represents the content of an HTTP request.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| RawDataContent | Defines basic data types of ArkTs. |
| Form | Defines HTTP simple form data. |
| MultipartForm | Defines HTTP multi-part form data. |
| GetDataCallback | Obtains any data. The input parameter is the maximum number of bytes allowed. |
| UploadFromStream | Uploads a file in stream mode. Since: 5.0.0(12) |
| UploadFromFile | Uploads a file from the client to the server. Since: 5.0.0(12) |
| INetworkInputQueue | Defines a write queue for synchronously writing request bodies, Since: 5.0.0(12) |
Defines HTTP simple form data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| fields | FormFields | No | No | HTTP simple form data fields. |
| keys | string[] | No | Yes | Sequence in which keys in the form are sent. If this parameter is set, the keys are sent based on this sequence list. Keys not in the list are not sent. If this parameter is not set, the default sending order follows the hash sequence of each key. Since: 6.0.1(21) |
constructor(fields: FormFields)
Provides the constructor used to create a Form object.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| fields | FormFields | Yes | HTTP simple form data fields. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
let headers: rcp.RequestHeaders = {
'accept': 'application/json'
};
let configuration: rcp.Configuration = {
transfer: {
timeout: { connectMs: 60000, transferMs: 60000 }
}
};
let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
let transferRange: rcp.TransferRange = { from: 100, to: 200 };
const simpleForm = new rcp.Form({
'key1': 'value1',
'key2': ['valueList0', 'valueList1'],
});
simpleForm.keys = ['key2', 'key1'];
let req = new rcp.Request('http://example.com', 'POST', headers, simpleForm, cookies, transferRange, configuration);
req.content = simpleForm; Defines HTTP multi-part form data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| fields | MultipartFormFields | No | No | HTTP multi-part form data fields. |
| boundary | string | No | Yes | Custom separator for an HTTP multi-part form. You can customize the boundary field to accurately separate and transfer form data when uploading a multi-part form. The boundary field cannot exceed 46 characters. Otherwise, a parameter error code will be reported. Since: 5.1.0(18) |
| keys | string[] | No | Yes | Key sequence in multi-part form data. If this parameter is set, the keys are sent based on this sequence list. Keys not in the list are not sent. If this parameter is not set, the default sending order follows the hash sequence of each key. Since: 6.0.1(21) |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. |
constructor(fields: MultipartFormFields)
Provides the constructor used to create a MultipartForm object.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| fields | MultipartFormFields | Yes | HTTP multi-part form data fields. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
let headers: rcp.RequestHeaders = {
'accept': 'application/json'
};
let configuration: rcp.Configuration = {
transfer: {
timeout: { connectMs: 60000, transferMs: 60000 }
}
};
let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
let transferRange: rcp.TransferRange = { from: 100, to: 200 };
const multiForm = new rcp.MultipartForm({
'key1': 'value1',
'key2': ['valueList0', 'valueList1'],
'key3': {
contentType: 'text/plain',
remoteFileName: 'RemoteFileName',
contentOrPath: '/file/to/Path',
},
});
multiForm.keys = ['key3', 'key1', 'key2'];
let req = new rcp.Request('http://example.com', 'POST', headers, multiForm, cookies, transferRange, configuration);
req.content = multiForm; constructor(fields: MultipartFormFields, boundary: string)
Provides the constructor used to create a MultipartForm object.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.1.0(18)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| fields | MultipartFormFields | Yes | HTTP multi-part form data fields. |
| boundary | string | Yes | Custom separator for an HTTP multi-part form. You can customize the boundary field to accurately separate and transfer form data when uploading a multi-part form. The boundary field cannot exceed 46 characters. Otherwise, a parameter error code will be reported. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
let headers: rcp.RequestHeaders = {
'accept': 'application/json'
};
let configuration: rcp.Configuration = {
transfer: {
timeout: { connectMs: 60000, transferMs: 60000 }
}
};
let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
let transferRange: rcp.TransferRange = { from: 100, to: 200 };
let Boundary: string = '--MULTIPARTFORM BEGIN AND END BOUNDARY'
const multiForm = new rcp.MultipartForm({
'key1': 'value1',
'key2': ['valueList0', 'valueList1'],
'key3': {
contentType: 'text/plain',
remoteFileName: 'RemoteFileName',
contentOrPath: '/file/to/Path',
},
}, Boundary)
multiForm.keys = ['key3', 'key1', 'key2'];
let req = new rcp.Request('http://example.com', 'POST', headers, multiForm, cookies, transferRange, configuration);
req.content = multiForm; type MultipartFormFields = { [k: string]: MultipartFormFieldValue | MultipartFormFieldValue[]; }
Defines fields in the HTTP multi-part form.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| { [k: string]: MultipartFormFieldValue | MultipartFormFieldValue[] } | MultipartFormFieldValue or MultipartFormFieldValue array, indicating any multi-part form field or an array of multi-part form fields, respectively. |
type MultipartFormFieldValue = FormFieldValue | FormFieldFileValue
Defines the values of fields in the HTTP multi-part form.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| FormFieldValue | FormFieldValue type, indicating a field value in the HTTP simple form. |
| FormFieldFileValue | FormFieldFileValue type, indicating file form data. |
type FormFields = { [k: string]: FormFieldValue | FormFieldValue[]; }
Defines fields in the HTTP simple form.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| { [k: string]: FormFieldValue | FormFieldValue[] } | FormFieldValue or FormFieldValue array, indicating any multi-part form field or an array of multi-part form fields, respectively. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const simpleForm: rcp.FormFields = {
'key1': 'value1',
'key2': ['valueList0', 'valueList1'],
}; type FormFieldValue = string | number | boolean | bigint
Defines the values of fields in the HTTP simple form.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| string | Field value of the string type. |
| number | Field value of the number type, which can be an integer or a floating point number. If the input value is greater than 2147483647, use the big integer type. |
| boolean | Field value of the Boolean type. |
| bigint | Field value of the big integer type. Use this type to input integers greater than 32 bits. |
type Path = string
Defines the file path type in the HTTP form data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| string | String type. The value can be any string. |
Defines the file content type in the HTTP form data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| content | string | ArrayBuffer | No | No | Content to be sent to the remote server. It can be any value. |
Defines file form data.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| contentType | ContentType | No | Yes | Content type of HTTP multi-part form data. The default value is undefined. |
| remoteFileName | string | No | Yes | Name of the file saved to a remote server. The default value is undefined. |
| contentOrPath | Path | FileContent | GetDataCallback | No | No | Content or the path of the file to be sent to the remote server. If the server supports HTTP2 and redirection, GetDataCallback cannot be used. In this case, use FileContent or Path instead. |
Example
import { rcp } from '@kit.RemoteCommunicationKit';
const formFieldFileValue: rcp.FormFieldFileValue = {
contentType: 'image/png',
remoteFileName: 'remoteFile1',
contentOrPath: '/path/to/file',
}; Defines cookies in an HTTP request.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| [name: string] | string | No | No | Cookies data. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const cookies: rcp.RequestCookies = {
'sessionID': 'abc123',
'userToken': 'xyz789',
// Add additional cookies here.
}; Sets the data transmission range. An HTTP request with this data requires the server to return only a part of the HTTP response.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| from | number | No | Yes | Start byte of the data to be transmitted. The default value is undefined. |
| to | number | No | Yes | End byte of the data to be transmitted. The default value is undefined. |
Response to an HTTP request.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| request | Request | Yes | No | HTTP request content to which the response is returned. |
| statusCode | number | Yes | No | Result code of an HTTP request. If the callback function is successfully executed, the result code defined in ResponseCode is returned. Otherwise, an error code is returned in the error field in AsyncCallback. |
| headers | ResponseHeaders | Yes | No | Response headers. |
| effectiveUrl | URL | Yes | Yes | Valid URL to which a request is redirected. The default value is undefined. |
| body | ArrayBuffer | Yes | Yes | The response content aligns with Content-type in the response header. The response content must be of the same data type returned by the server. The default maximum download byte limit is 50 MB. If the size exceeds 50 MB, to mitigate memory overflow, you need to stream the data using OnDataReceive. |
| downloadedTo | DownloadedTo | Yes | Yes | Path for downloading content. When downloading to a file object or using a file descriptor, no callback information is set by default. Since: 5.0.0(12) |
| debugInfo | DebugInfo[] | Yes | Yes | Debugging information associated with a response. The default value is undefined. |
| timeInfo | TimeInfo | Yes | Yes | Timer information in each phase of HTTP request processing. The default value is undefined. |
| cookies | ResponseCookie[] | Yes | Yes | Cookie array in a response. |
| httpVersion | HttpVersion | Yes | Yes | HTTP version. Since: 5.0.0(12) |
| reasonPhrase | string | Yes | Yes | reasonPhrase of an HTTP status line, which provides a descriptive message associated with a numerical status code. Since: 5.0.0(12) |
| cacheInfo | CacheInfo | Yes | Yes | Cache information, including the cache duration and original HTTP request ID. This attribute has a value only when an HTTP response is obtained from the cache. Otherwise, the value is undefined. Since: 6.0.0(20) |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
// The following describes how to modify the response, which is for reference only.
interface ChangeableResponse {
request: rcp.Request;
statusCode: number;
headers: rcp.ResponseHeaders;
effectiveUrl?: rcp.URL;
body?: ArrayBuffer;
downloadedTo?: rcp.DownloadedTo;
debugInfo?: rcp.DebugInfo[];
timeInfo?: rcp.TimeInfo;
cookies?: rcp.ResponseCookie[];
httpVersion?: rcp.HttpVersion;
reasonPhrase?: string;
cacheInfo?: rcp.CacheInfo;
}
async function TestRcp() {
const session = rcp.createSession();
const resp = await session.get('https://www.example.com');
const changeableResponse = resp as ChangeableResponse;
changeableResponse.headers = HEADERS // Define this information based on your service needs.
changeableResponse.statusCode = STATUSCODE // Define this information based on your service needs.
} toString(): string | null
Converts a response body into a character string. If the conversion fails, null is returned.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Returns:
| Type | Description |
|---|---|
| string | null | UTF-8 character string (if the HTTP response body is not in UTF-8 format) or null value. |
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
const request = new rcp.Request('https://www.example.com');
session.fetch(request).then((response: rcp.Response) => {
if (response) {
console.info(`Succeeded in fetching the response, response: ${response.toString()}`);
}
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); toJSON(): object | null
Returns the default JSON deserialization result. For details about how to customize the JSON deserialization mode, please refer to JSON Parsing and Generation.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Returns:
| Type | Description |
|---|---|
| object | null | JSON character string containing toString() (if no exception occurs) or null value (if the body is not in JSON format). |
Example:
import { BusinessError } from '@kit.BasicServicesKit';
import { rcp } from '@kit.RemoteCommunicationKit';
const session = rcp.createSession();
const request = new rcp.Request('https://www.example.com');
session.fetch(request).then((response: rcp.Response) => {
if (response) {
let resJson = response.toJSON();
console.info(`Succeeded in fetching the response, response: ${JSON.stringify(resJson)}`);
}
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); toJSON(param: json.ParseOptions): object | null
Parses the string returned by the toString method based on the JSON-based parsing settings and returns the parsing result. For details, please refer to JSON Parsing and Generation.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.1.0(23)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| param | json.ParseOptions | Yes | Parsing settings. The mode for processing BigInt is supported. |
Returns:
| Type | Description |
|---|---|
| object | null | Result of parsing the string converted by the toString() method. If an exception occurs during the parsing, null is returned. The toJSON method is used to process the body. If the body is not in JSON format, null is also returned. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { JSON } from '@kit.ArkTS';
import { BusinessError } from '@kit.BasicServicesKit';
const session = rcp.createSession();
const request = new rcp.Request('https://www.example.com');
session.fetch(request).then((response: rcp.Response) => {
if (response) {
const obj = response.toJSON({ bigIntMode: JSON.BigIntMode.PARSE_AS_BIGINT }); // This is for reference only. The actual response body must be in JSON format and may contain big integer data.
console.info(`Succeeded in fetching the response, response json result: ${JSON.stringify(obj)}`);
}
}).catch((err: BusinessError) => {
console.error(`err: error code is ${err.code}, error data is ${err.data}`);
}); Response data of the HTTP request. The response data supports Sendable.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| requestId | string | Yes | No | Sequence number of the request to be sent. |
| statusCode | number | Yes | No | Status code of the HTTP request. |
| headers | ResponseHeaders | Yes | No | Response headers. |
| effectiveUrl | string | Yes | Yes | Valid URL to which a request is redirected, which is a character string. The default value is undefined. |
| body | ArrayBuffer | Yes | Yes | The response content is returned based on content-type in the response header and must match the data type returned by the server. |
| downloadedTo | DownloadedTo | Yes | Yes | Path for downloading content. When downloading to a file object or using a file descriptor, no callback information is set by default. |
| debugInfo | DebugInfo[] | Yes | Yes | Debugging information associated with a response. The default value is undefined. |
| timeInfo | TimeInfo | Yes | Yes | Timer information in each phase of HTTP request processing. The default value is undefined. |
| cookies | ResponseCookie[] | Yes | Yes | Cookie array in a response. |
| httpVersion | HttpVersion | Yes | Yes | HTTP version. |
| reasonPhrase | string | Yes | Yes | Text description about an HTTP request status code. |
| cacheInfo | CacheInfo | Yes | Yes | Cache information, including the cache duration and original HTTP request ID. This attribute has a value only when an HTTP response is obtained from the cache. Otherwise, the value is undefined. |
type ResponseHeaders = { [k: string]: string | string[] | undefined; 'accept-ranges'?: 'none' | 'bytes' | (string & NonNullable<unknown>); 'allow'?: HttpMethod | HttpMethod[]; 'cache-control'?: string | string[]; 'content-encoding'?: ContentCoding; 'content-range'?: string; 'content-type'?: ContentType; 'date'?: string; 'etag'?: string; 'expires'?: string; 'location'?: string; 'retry-after'?: string; 'set-cookie'?: string | string[]; 'server'?: string; 'www-authenticate'?: string | string[]; }
Defines the response header type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
{ [k: string]: string | string[] | undefined; 'accept-ranges'?: 'none' | 'bytes' | (string & NonNullable<unknown>); 'allow'?: HttpMethod | HttpMethod[]; 'cache-control'?: string | string[]; 'content-encoding'?: ContentCoding; 'content-range'?: string; 'content-type'?: ContentType; 'date'?: string; 'etag'?: string; 'expires'?: string; 'location'?: string; 'retry-after'?: string; 'set-cookie'?: string | string[]; 'server'?: string; 'www-authenticate'?: string | string[]; } | If the key is [k: string]: string | string[] | undefined, the value contains one or more key-value pairs. In a key-value pair, the key can be any string and the value can be a string, string array, or undefined. 'accept-ranges' indicates the accept-ranges data in the response header. If the key is 'allow', the value can be any value of the HttpMethod or HttpMethod[] type. If the key is 'cache-control', the value can be any string or string array. If the key is 'content-encoding', the value can be any value of the ContentCoding type. If the key is 'content-range', the value can be any string. If the key is 'content-type', the value can be any value of the ContentType type. If the key is 'date', the value can be any string. If the key is 'etag', the value can be any string. If the key is 'expires', the value can be any string. If the key is 'location', the value can be any string. If the key is 'retry-after', the value can be any string. If the key is 'set-cookie', the value can be any string or string array. If the key is 'server', the value can be any string. If the key is 'www-authenticate', the value can be any string or string array. |
Defines cookies in an HTTP response.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| name | string | No | No | Cookie name. |
| value | string | No | Yes | Cookie value. |
| domain | string | No | Yes | Cookie domain name. |
| path | string | No | Yes | Cookie path. |
| expires | string | No | Yes | Cookie expiration date. |
| maxAge | number | No | Yes | Maximum storage duration of cookies, in seconds. |
| isSecure | true | No | Yes | Indicates whether cookies can be sent only through secure connections. The options are true (yes) and false (no). The default value is true. |
| httpOnly | true | No | Yes | Indicates whether active content, such as page scripts, can access cookies. The options are true (yes) and false (no). The default value is true. |
| sameSite | string | No | Yes | Specifies when cookies are sent in cross-site requests. |
| rawSize | number | No | Yes | Cookie size. |
| cookieAttributes | CookieAttributes | No | Yes | All properties in the response cookies. |
Processes debugging information in a request/response.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| type | DebugEvent | No | No | Debugging information type. |
| data | ArrayBuffer | No | No | Debugging information. |
type HttpVersion = '1.0' | '1.1' | '2' | '3' | 'unknown'
HTTP version.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| '1.0' | HTTP version 1.0. The value is a character string. |
| '1.1' | HTTP version 1.1. The value is a character string. |
| '2' | HTTP version 2. The value is a character string. |
| '3' | HTTP version 3. The value is a character string. |
| 'unknown' | Unknown HTTP version. The value is a character string. |
Defines time-related information for HTTP network requests in each request phase.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| nameLookupTimeMs | number | No | No | Time required for DNS resolution, in milliseconds. |
| connectTimeMs | number | No | No | Connection setup time, in milliseconds. |
| tlsHandshakeTimeMs | number | No | No | Time elapsed till the TLS handshake with the remote host or proxy server, in milliseconds. Since: 5.0.0(12) |
| preTransferTimeMs | number | No | No | Time elapsed till the transmission starts, in milliseconds. |
| startTransferTimeMs | number | No | No | Transmission start time, in milliseconds. |
| totalTimeMs | number | No | No | Total duration of a request, in milliseconds. |
| redirectTimeMs | number | No | No | Time required for redirection, in milliseconds. |
TimeInfo timeline: request initiation (time 0) -> nameLookupTimeMs (DNS resolution) -> connectTimeMs (connection establishment) -> tlsHandshakeTimeMs (TLS handshake) -> data request arriving at the server (preTransferTimeMs) -> first packet received from the server (startTransferTimeMs). All time points are measured from the request initiation (0). For example, if tlsHandshakeTimeMs is 150.1ms, it means that the time taken from the request initiation (time 0) until the completion of the TLS handshake is 150.1 milliseconds.
Methods for calculating the durations of key phases in network requests are as follows:
First packet delivery duration: startTransferTimeMs – preTransferTimeMs
TLS handshake duration (excluding the connection setup time): tlsHandshakeTimeMs – connectTimeMs
Duration for receiving the remaining data: totalTimeMs – startTransferTimeMs
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
// 1. Create a session and define the request URL.
const session = rcp.createSession();
const requestURL = 'https://www.example.com';
// 2. To track and analyze the time consumed for each phase during a request, enable this switch.
const configuration: rcp.Configuration = {
tracing: {
collectTimeInfo: true
}
}
// 3. Create a request.
const request = new rcp.Request(requestURL, 'GET');
request.configuration = configuration;
// 4. Use FETCH to initiate a network request carrying the configuration.
session.fetch(request).then((response: rcp.Response) => {
// Parameters in timeInfo may be undefined. Therefore, before performing calculation based on any two parameters, add the logic to determine whether the parameters are undefined.
if (!response.timeInfo) {
console.error(`TimeInfo is undefined ${response.timeInfo}`);
return;
}
let remainderDataTime = response.timeInfo?.totalTimeMs - response.timeInfo?.startTransferTimeMs;
let firstPackageTime = response.timeInfo?.startTransferTimeMs - response.timeInfo?.preTransferTimeMs;
let TLSTime = response.timeInfo?.tlsHandshakeTimeMs - response.timeInfo?.connectTimeMs;
console.info(`First packet delivery duration${firstPackageTime}`);
console.info(`TLS handshake duration (excluding the connection setup time)${TLSTime}`);
console.info(`Duration for receiving the remaining data${remainderDataTime}`);
}).catch((err: BusinessError) => {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
}) type CookieAttributes = { [k: string]: string | undefined; }
Defines the cookie attribute type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| { [k: string]: string | undefined; } | Object containing one or more key-value pairs. In a key-value pair, the key can be any string and the value can be any string or undefined. |
type ContentType = 'application/json' | 'text/plain' | 'multipart/form-data' | 'application/octet-stream' | 'application/x-www-form-urlencoded' | (string & NonNullable<unknown>)
Defines the content type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'application/json' | 'application/json': The content is a JSON string. |
| 'text/plain' | 'text/plain': The content is text. |
| 'multipart/form-data' | 'multipart/form-data': The content is form data. |
| 'application/octet-stream' | 'application/octet-stream': The content is a binary data stream. |
| 'application/x-www-form-urlencoded' | 'application/x-www-form-urlencoded': The content is form data. |
| (string & NonNullable<unknown>) | string & NonNullable<unknown>: The content can be any non-empty string. |
Defines the certificate context.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| pemCerts | string[] | No | No | PEM certificate |
| x509Certs | X509Cert[] | No | No | X.509 certificate object. |
| host | string | No | No | Domain name of the server to which a connection is set up. |
| ip | string | No | No | IP address of the server to which a connection is set up. |
type ValidationCallback = (context: ValidationContext) => boolean | Promise<boolean>
Defines the custom certificate validation function. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| context | ValidationContext | Yes | Certificate context. |
Returns:
| Type | Description |
|---|---|
| boolean | Promise<boolean> | Callback or promise that returns true (verification successful) or false (verification failed). |
type TlsV13SpecificCipherSuite = 'TLS_AES_128_GCM_SHA256' | 'TLS_AES_256_GCM_SHA384' | 'TLS_CHACHA20_POLY1305_SHA256'
Cipher suite supported by TLS 1.3 or later. This framework has built-in cipher suite priorities, where custom options are also recorded.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| 'TLS_AES_128_GCM_SHA256' | Supported cipher suite: 'TLS_AES_128_GCM_SHA256'. The value is a character string. |
| 'TLS_AES_256_GCM_SHA384' | Supported cipher suite: 'TLS_AES_256_GCM_SHA384'. The value is a character string. |
| 'TLS_CHACHA20_POLY1305_SHA256' | Supported cipher suite: 'TLS_CHACHA20_POLY1305_SHA256'. The value is a character string. |
type TlsV12SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | 'TLS_RSA_WITH_AES_128_GCM_SHA256' | 'TLS_RSA_WITH_AES_256_GCM_SHA384'
Cipher suite supported by TLS 1.2 or later.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: 'TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256'. The value is a string. |
| 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: 'TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256'. The value is a string. |
| 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: 'TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384'. The value is a string. |
| 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: 'TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384'. The value is a string. |
| 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' | Supported cipher suite: 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256'. The value is a string. |
| 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' | Supported cipher suite: 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256'. The value is a string. |
| 'TLS_RSA_WITH_AES_128_GCM_SHA256' | Supported cipher suite: 'TLS_RSA_WITH_AES_128_GCM_SHA256'. The value is a string. |
| 'TLS_RSA_WITH_AES_256_GCM_SHA384' | Supported cipher suite: 'TLS_RSA_WITH_AES_256_GCM_SHA384'. The value is a string. |
type TlsV10SpecificCipherSuite = 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_AES_128_CBC_SHA' | 'TLS_RSA_WITH_AES_256_CBC_SHA' | 'TLS_RSA_WITH_3DES_EDE_CBC_SHA'
Cipher suite supported by TLS 1.0 or later.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: 'TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA'. The value is a string. |
| 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: 'TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA'. The value is a string. |
| 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: 'TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA'. The value is a string. |
| 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: 'TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA'. The value is a string. |
| 'TLS_RSA_WITH_AES_128_CBC_SHA' | Supported cipher suite: 'TLS_RSA_WITH_AES_128_CBC_SHA'. The value is a string. |
| 'TLS_RSA_WITH_AES_256_CBC_SHA' | Supported cipher suite: 'TLS_RSA_WITH_AES_256_CBC_SHA'. The value is a string. |
| 'TLS_RSA_WITH_3DES_EDE_CBC_SHA' | Supported cipher suite: 'TLS_RSA_WITH_3DES_EDE_CBC_SHA'. The value is a string. |
type CipherSuite = TlsV13CipherSuite
Declares the cipher suite.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| TlsV13CipherSuite | Cipher suite defined in TlsV13CipherSuite. |
type TlsV13CipherSuite = TlsV12CipherSuite | TlsV13SpecificCipherSuite
Declares the cipher suite for TLS 1.3, which is also compatible with TLS 1.2.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| TlsV12CipherSuite | TlsV12CipherSuite type. |
| TlsV13SpecificCipherSuite | TlsV13SpecificCipherSuite type. |
type TlsV12CipherSuite = TlsV11CipherSuite | TlsV12SpecificCipherSuite
Declares the cipher suite for TLS 1.2, which is also compatible with TLS 1.1.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| TlsV11CipherSuite | TlsV11CipherSuite type. |
| TlsV12SpecificCipherSuite | TlsV12SpecificCipherSuite type. |
type TlsV11CipherSuite = TlsV10CipherSuite
Declares the cipher for TLS 1.1, which is the same as that of TLS 1.0.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| TlsV10CipherSuite | TlsV10CipherSuite type. |
type TlsV10CipherSuite = TlsV10SpecificCipherSuite
Declares the cipher suite for TLS 1.0.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Type | Description |
|---|---|
| TlsV10SpecificCipherSuite | TlsV10SpecificCipherSuite type. |
TLS 1.3 selector function, which is used to select the TLS version and matching cipher suite.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| tlsVersion | 'TlsV1.3' | No | No | TLS 1.3. |
| cipherSuite | TlsV13CipherSuite[] | No | Yes | Cipher suite for TLS 1.3. |
TLS 1.2 selector function, which is used to select the TLS version and matching cipher suite.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| tlsVersion | 'TlsV1.2' | No | No | TLS 1.2. |
| cipherSuite | TlsV12CipherSuite[] | No | Yes | Cipher suite for TLS 1.2. |
TLS 1.1 selector function, which is used to select the TLS version and matching cipher suite.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| tlsVersion | 'TlsV1.1' | No | No | TLS 1.1. |
| cipherSuite | TlsV11CipherSuite[] | No | Yes | Cipher suite for TLS 1.1. |
TLS 1.0 selector function, which is used to select the TLS version and matching cipher suite.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| tlsVersion | 'TlsV1.0' | No | No | TLS 1.0. |
| cipherSuite | TlsV10CipherSuite[] | No | Yes | Cipher suite for TLS 1.0. |
type ContentCoding = 'aes128gcm' | 'br' | 'compress' | 'deflate' | 'exi' | 'gzip' | 'pack200-gzip' | 'x-compress' | 'x-gzip' | 'zstd' | (string & NonNullable<unknown>)
Pre-defines the content encoding type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'aes128gcm' | Encode content using the AES-128-GCM encryption algorithm for symmetric encryption. |
| 'br' | Encode content using the Brotli algorithm, which is designed for high compression ratios, especially suitable for web pages and documents. |
| 'compress' | Encode content using the Unix compress algorithm. |
| 'deflate' | Encode content using the DEFLATE algorithm, which offers high compression ratios and relatively fast compression speeds. |
| 'exi' | Encode content using the Efficient XML Interchange (EXI) format, which is designed for high compression ratios of XML data. |
| 'gzip' | Encode content using the GZIP algorithm, which is a widely used compression method for web servers and apps. |
| 'pack200-gzip' | Encode content using the Pack200 and GZIP algorithms. |
| 'x-compress' | Encode content using Zlib's compress method. |
| 'x-gzip' | Encode content using Zlib's gzip method, which employs the DEFLATE compression algorithm to achieve high compression ratios and fast compression speeds. |
| 'zstd' | Encode content using the Zstandard algorithm, which is designed for high compression ratios, especially suitable for databases and files. |
| (string & NonNullable<unknown>) | Option used to ensure that the value of the ContentCoding type is a non-empty string. |
type ResponseValidationCallback = (response: Response) => boolean | Promise<boolean>
Response verification callback function. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| response | Response | Yes | Response transferred by the framework, which needs to be verified. |
Returns:
| Type | Description |
|---|---|
| boolean | Promise<boolean> | Callback or promise that returns true (verification successful) or false (verification failed). |
Defines processing settings.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| validateResponse | 'default' | ResponseValidationCallback | No | Yes | Response processing type. Either no processing is performed (default type) or ResponseValidationCallback is called to verify the response. |
type GetDataCallback = (maxSize: number) => ArrayBuffer | Promise<ArrayBuffer>
Callback triggered when data is sent. This callback is used to obtain the data to be sent, with the maximum number of bytes allowed as the input parameter. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| maxSize | number | Yes | Maximum number of bytes. The returned value is an ArrayBuffer value returned directly or asynchronously using a promise. The return value can be any value of the ArrayBuffer type. |
Returns:
| Type | Description |
|---|---|
| ArrayBuffer | Callback used to return the sent data. Applicable versions: 4.1.0(11) |
| ArrayBuffer | Promise<ArrayBuffer> | Callback or promise that returns the data to be sent. Applicable versions: 5.0.0(12)+ |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';
let read = false;
function testGetDataCallback() {
try {
const session = rcp.createSession();
const request = new rcp.Request('https://www.example.com');
// Create a getDataCallback object.
const getDataCallback: rcp.GetDataCallback = (maxSize: number) => {
if (read) {
return Promise.resolve(new ArrayBuffer(0));
}
read = true;
// Convert the test data of the string type into ArrayBuffer and use it as the return value of GetDataCallback.
const data = "Hello World";
const buffer = new ArrayBuffer(data.length);
const uint8Array = new Uint8Array(buffer);
new util.TextEncoder().encodeIntoUint8Array(data, uint8Array);
return Promise.resolve(buffer);
}
// Assign the getDataCallback object to request.content.
request.content = getDataCallback;
session.fetch(request).then((response) => {
console.info(`Succeeded in fetch the response ${response.toString()}`);
session.close();
}).catch((error: BusinessError) => {
console.error(`Error: error code is ${error.code}, error data is ${error.data}`);
session.close();
});
} catch (error) {
console.error(`Error: error code is ${error.code}, error data is ${error.data}`);
}
} type DynamicExclusionRule = (url: URLOrString) => boolean
Obtains whether to exclude input URLs from proxy processing.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | Union set of URL objects or strings representing URLs. Method whose input parameter type is URLOrString and return value is of the boolean value. The return value is true or false. |
Returns:
| Type | Description |
|---|---|
| boolean | Indicates whether to use the proxy. The return value is true or false. |
Represents a single static DNS rule that associates a specific IP address with a host name and a port number. This configuration is used in StaticDnsRule for defining DNS mapping information.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| host | string | No | No | Host name to which the static DNS rule is applied. |
| port | number | No | No | Port number to which the static DNS rule is applied. The value ranges from 0 to 65535. |
| ipAddresses | IpAddress[] | No | No | Array of IP addresses to associate with the specified host name and port number. |
type StaticDnsRules = StaticDnsRule[]
Associates specified IP addresses with host names and port numbers. This configuration applies to scenarios where IP mapping needs to be customized for specific domain names and port numbers.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| StaticDnsRule[] | StaticDnsRule array. |
type DynamicDnsRule = (host: string, port: number) => IpAddress[]
Obtains IP addresses based on the specified host name and port number.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| host | string | Yes | Host name. |
| port | number | Yes | Port number. |
Returns:
| Type | Description |
|---|---|
| IpAddress[] | An array of IP addresses. |
Defines custom proxy settings in ProxyConfiguration, including the proxy server URL, exclusions, and other security settings.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| url | URLOrString | No | No | Custom proxy server URL. |
| createTunnel | 'auto' | 'always' | No | Yes | Indicates when a proxy tunnel needs to be established. Tunneling is a process where an HTTP CONNECT request is sent to a proxy server, instructing it to establish a connection to the remote host of a specified port number. Once this connection is set up, all subsequent traffic is routed through the proxy. The default value is 'auto'. 'auto': A tunnel will be created for HTTPS traffic but not for HTTP traffic. 'always': Tunneling is enabled for all traffic. |
| exclusions | URLOrString | URLOrString[] | DynamicExclusionRule | No | Yes | URLs to be excluded from proxy processing (in the format 'http://exclude.example.com' or ['http://exclude1.com', 'http://exclude2.com']). The default value is undefined. |
| security | SecurityConfiguration | No | Yes | Proxy security settings. The default value is undefined. |
Collects detailed information events. The collected information events are returned in the debugInfo field of Response. This API will occupy memory resources. You are advised to call it only in the development and debugging phases.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| textual | boolean | No | Yes | Indicates whether to collect text events. The options are true (yes) and false (no). The default value is false. |
| incomingHeader | boolean | No | Yes | Indicates whether to collect header transfer-in events. The options are true (yes) and false (no). The default value is false. |
| outgoingHeader | boolean | No | Yes | Indicates whether to collect header transfer-out events. The options are true (yes) and false (no). The default value is false. |
| incomingData | boolean | No | Yes | Indicates whether to collect data transfer-in events. The options are true (yes) and false (no). The default value is false. |
| outgoingData | boolean | No | Yes | Indicates whether to collect data transfer-out events. The options are true (yes) and false (no). The default value is false. |
| incomingSslData | boolean | No | Yes | Indicates whether to collect SSL/TLS data transfer-in events. The options are true (yes) and false (no). The default value is false. |
| outgoingSslData | boolean | No | Yes | Indicates whether to collect SSL/TLS data transfer-out events. The options are true (yes) and false (no). The default value is false. |
| srcAddr | boolean | No | Yes | Indicates whether to collect client address information. true: The client address and port number are collected. false: The client address and port number are not collected. The default value is false. Since: 6.0.0(20) |
| dstAddr | boolean | No | Yes | Indicates whether to collect server address information. true: The server address and port number are collected. false: The server address and port number are not collected. The default value is false. Since: 6.0.0(20) |
| redirectCount | boolean | No | Yes | Indicates whether to collect the number of redirections. true: yes false: no The default value is false. Since: 6.1.0(23) |
Applies custom logic to handle various operations during HTTP request/response processing.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| onDataReceive | OnDataReceive | No | Yes | Callback triggered when a part of an HTTP response body is returned. The default value is undefined. Use this callback to receive data when the data size exceeds 50 MB. Then the body field of the returned Response object will no longer contain data. |
| onUploadProgress | OnUploadProgress | No | Yes | Callback triggered to process the upload progress in a response. The default value is undefined. |
| onDownloadProgress | OnDownloadProgress | No | Yes | Callback triggered to process the download progress in a response. The default value is undefined. |
| onHeaderReceive | OnHeaderReceive | No | Yes | Callback triggered to process headers received in a response. The default value is undefined. |
| onDataEnd | OnDataEnd | No | Yes | Callback triggered when data transfer is completed. The default value is undefined. |
| onCanceled | OnCanceled | No | Yes | Callback triggered when a request or response is canceled. The default value is undefined. |
| onTimeInfo | OnTimeInfo | No | Yes | Callback triggered when an HTTP request fails or succeeds. The default value is undefined. Since: 5.0.3(15) |
| onStatusCodeReceive | OnStatusCodeReceive | No | Yes | Callback triggered to process the status code received in a response. The default value is undefined. Since: 6.0.0(20) |
HTTP request timeout settings for connection and data transmission.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| connectMs | number | No | Yes | Maximum duration for establishing a connection, in milliseconds. If the connection setup duration exceeds this limit, the connection times out. The default value is 60000. |
| transferMs | number | No | Yes | Maximum duration for data transmission, in milliseconds. If the data transmission duration exceeds this limit, the transmission times out. The default value is 60000. |
| inactivityMs | number | No | Yes | Maximum duration for allowing no data transmission or connection activity. This setting is used to prevent long-idle connections in cases where the time interval between receiving or sending data to the server cannot exceed a certain value. By default, no timeout is set, indicating that the duration is not limited. Since: 5.0.0(12) |
Verifies the authenticity of a server's certificate by comparing its public key's SHA-256 hash to a predefined value.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.0(12)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'public-key' | No | No | Certification verification type. |
| publicKeyHash | string | No | No | Public key hash. |
| hashAlgorithm | 'SHA-256' | No | No | Algorithm used to calculate the public key hash value. |
Defines a session listener.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| onCanceled | OnCanceled | No | Yes | Callback triggered when a session is canceled. The default value is undefined. |
| onClosed | OnClosed | No | Yes | Callback triggered when a session is closed. The default value is undefined. |
Represents the credential used for server identity verification in a session, including the user name and password.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| username | string | No | No | User name used for verification. The default value is ' '. |
| password | string | No | No | Password used for verification. The default value is ' '. |
type TlsVersion = 'TlsV1.0' | 'TlsV1.1' | 'TlsV1.2' | 'TlsV1.3'
Defines the available TLS version options.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Type | Description |
|---|---|
| 'TlsV1.0' | TLS 1.0. |
| 'TlsV1.1' | TLS 1.1. |
| 'TlsV1.2' | TLS 1.2. |
| 'TlsV1.3' | TLS 1.3. |
type DebugEvent = 'text' | 'headerIn' | 'headerOut' | 'dataIn' | 'dataOut' | 'sslDataIn' | 'sslDataOut' | 'srcAddr' | 'dstAddr' | 'redirectCount'
Defines the debugging event type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'text' | The debugging event is related to the text content of the HTTP response. |
| 'headerIn' | The debugging event is related to the header information of the HTTP response received by the client. |
| 'headerOut' | The debugging event is related to the header information of the HTTP request sent by the client. |
| 'dataIn' | The debugging event is related to the body information of the HTTP response received by the client. |
| 'dataOut' | The debugging event is related to the body information of the HTTP request sent by the client. |
| 'sslDataIn' | The debugging event is related to the HTTP response data received through the SSL/TLS protocol. |
| 'sslDataOut' | The debugging event is related to the HTTP request data sent through the SSL/TLS protocol. |
| 'srcAddr' | The debugging event is related to obtaining the client address and port. Since: 6.0.0(20) |
| 'dstAddr' | The debugging event is related to obtaining the server address and port. Since: 6.0.0(20) |
| 'redirectCount' | The debugging event is related to obtaining the number of redirections. Since: 6.1.0(23) |
type AuthenticationType = 'basic' | 'ntlm' | 'digest'
Defines different identity verification types in a session.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
| Type | Description |
|---|---|
| 'basic' | The basic identity authentication mode is used. The input user name and password are combined into a character string and encoded using Base64 for authentication. |
| 'ntlm' | The NT LAN Manager authentication mode is used. |
| 'digest' | The HTTP digest authentication mode is used, generating authentication information by hashing the user name, password, and other information. |
type OnCanceled = (request?: Request) => void
Callback triggered when a request or session is canceled.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| request | Request | No | HTTP request that triggers the callback. Since: 6.0.0(20) |
type OnClosed = () => void
Callback triggered when a session is closed.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
type OnDataReceive = (incomingData: ArrayBuffer, request?: Request) => number | void | Promise<void>
Callback triggered when an HTTP body is returned. Use this callback to receive data when the data size exceeds 50 MB. Then the body field of the returned Response object will no longer contain data. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| incomingData | ArrayBuffer | Yes | HTTP data that is received. |
| request | Request | No | HTTP request that triggers the callback. Since: 6.0.0(20) |
Returns:
| Type | Description |
|---|---|
| number | Callback used to return data of the number type, indicating the number of processed bytes. Applicable versions: 4.1.0(11) |
| number | void | Promise<void> | Callback that returns the number of processed bytes or no value, or promise that returns no result. Applicable versions: 5.0.0(12)+ |
type OnUploadProgress = (totalSize: number, transferredSize: number, request?: Request) => void
Callback triggered when the upload progress is displayed. If the total data size cannot be obtained, this callback may not be triggered.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| totalSize | number | Yes | Total size of the data to be uploaded. |
| transferredSize | number | Yes | Size of the data that has been uploaded. |
| request | Request | No | HTTP request that triggers the callback. Since: 6.0.0(20) |
type OnDownloadProgress = (totalSize: number, transferredSize: number, request?: Request) => void
Callback triggered when the download progress is displayed. If the total data size cannot be obtained, this callback may not be triggered.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| totalSize | number | Yes | Total size of the data to be downloaded. |
| transferredSize | number | Yes | Size of the data that has been downloaded. |
| request | Request | No | HTTP request that triggers the callback. Since: 6.0.0(20) |
type OnHeaderReceive = (headers: ResponseHeaders, request?: Request) => void
Callback triggered when an HTTP header is returned.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| headers | ResponseHeaders | Yes | The HTTP response header is passed, and no value is returned. |
| request | Request | No | HTTP request that triggers the callback. Since: 6.0.0(20) |
type OnDataEnd = (request?: Request) => void
Callback triggered when HTTP transmission is completed.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 4.1.0(11)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| request | Request | No | HTTP request that triggers the callback. Since: 6.0.0(20) |
type OnTimeInfo = (timeInfo: TimeInfo, request?: Request) => void
Represents the callback triggered when an HTTP request is successful or fails. If a request is successful, the timer information of each phase of the request can be obtained. If a request fails, the timer of each phase before the failure can be obtained.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 5.0.3(15)
Parameters:
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
import { BusinessError } from '@kit.BasicServicesKit';
// 1. Create a session and define the request URL and request.
const session = rcp.createSession();
const requestURL = 'https://www.example.com';
const request = new rcp.Request(requestURL);
// 2. Set configuration for the request, in which you need to configure the onTimeInfo callback function to obtain time information related to the network request.
request.configuration = {
tracing: {
httpEventsHandler: {
onTimeInfo: (timeInfo: rcp.TimeInfo) => {
console.info(`Time information for each phase in the HTTP request. ${JSON.stringify(timeInfo)}`);
let remainderDataTime = timeInfo?.totalTimeMs - timeInfo?.startTransferTimeMs;
let firstPackageTime = timeInfo?.startTransferTimeMs - timeInfo?.preTransferTimeMs;
let TLSTime = timeInfo?.tlsHandshakeTimeMs - timeInfo?.connectTimeMs;
console.info(`First packet delivery duration${firstPackageTime}`);
console.info(`TLS handshake duration (excluding the connection setup time)${TLSTime}`);
console.info(`Duration for receiving the remaining data${remainderDataTime}`);
},
},
},
};
// 3. Use FETCH to initiate a network request carrying the configuration defined above.
session.fetch(request).then((response) => {
if (response) {
console.info(`Succeeded in fetching the response. The statusCode of the response is ${response.statusCode}`);
session.close();
}
}).catch((err: BusinessError) => {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
}) type OnStatusCodeReceive = (statusCode: number, request?: Request) => void
Defines the callback triggered when an HTTP request is successful or fails, from which you can obtain the response status code.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| statusCode | number | Yes | HTTP status code. |
| request | Request | No | HTTP request that triggers the callback. |
Controls the caching behavior and policies relevant to HTTP requests, including the resource cache policy, update mechanism, and storage rules.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| expirationPolicy | TimeLimitedExpirationPolicy | No | Yes | Expiration policy of cache records created for HTTP requests. This setting takes precedence over the HTTP response expiration policy. |
| keepCache | boolean | No | Yes | Indicates whether to retain the cache. The options are true (yes) and false (no). The default value is false. If this parameter is set to true, cache resources will not be cleared for requests using insecure HTTP methods (PUT, POST, or DELETE). |
| noCache | boolean | No | Yes | Indicates whether to add no-cache to the request header. The options are true (yes) and false (no). The default value is false. If this parameter is set to true, the client must verify the validity of a resource with the server before using the cache record. |
| noStore | boolean | No | Yes | Indicates whether to add no-store to the request header. The options are true (yes) and false (no). The default value is false. If this parameter is set to true, all caching of request or response content is strictly prohibited, ensuring that sensitive data is not persisted. |
| maxAge | TimeInterval | No | Yes | Validity period of a cached resource, during which the client can use the cached data directly without requesting it from the server again. |
| maxStale | TimeInterval | No | Yes | Time window, in seconds, during which the client can use an expired cache record. This improves data availability. |
| minFresh | TimeInterval | No | Yes | Required duration for a keeping a response from the server fresh. |
| noTransform | boolean | No | Yes | Indicates whether to add no-transform to the request header. The options are true (yes) and false (no). The default value is false. If this parameter is set to true, the cache server is prohibited from converting the response content (for example, compressing), ensuring consistency with the original response content. |
| onlyIfCached | boolean | No | Yes | Indicates whether to add only-if-cached to the request header. The options are true (yes) and false (no). The default value is false. If this parameter is set to true, the client can use only cached resources. If no cached resource is found, the request directly fails and the client cannot request the resource from the server again. |
Defines cache information, including the original HTTP request ID and the cache duration of a cache record.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| originalRequestId | string | No | No | Original HTTP request ID used when a cache record is created. |
| age | TimeInterval | No | No | Elapsed cache duration. |
type ExpirationPolicy = NeverExpirationPolicy | TimeLimitedExpirationPolicy
Defines the cache expiration policy types.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Type | Description |
|---|---|
| NeverExpirationPolicy | Permanent cache expiration policy. |
| TimeLimitedExpirationPolicy | Time-constrained expiration policy. |
Defines the permanent cache expiration policy. Under this policy, cache records will be stored until the cache size limit is reached.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'never' | No | No | Indicates that the permanent expiration policy is used. |
type TimeLimitedExpirationPolicy = AbsoluteTimeExpirationPolicy | RelativeTimeExpirationPolicy | SlidingTimeExpirationPolicy
Time-constrained expiration policy.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Type | Description |
|---|---|
| AbsoluteTimeExpirationPolicy | Defines the absolute time-based expiration policy. A cache record expires when a specific time is reached. |
| RelativeTimeExpirationPolicy | Defines the relative time-based expiration policy. A cache record expires after a specified period. |
| SlidingTimeExpirationPolicy | Defines the sliding time window-based expiration policy. A cache record expires if it is not accessed within a specified time period. Each time it is accessed, its expiration timer is reset. |
Defines the absolute time-based expiration policy. A cache record expires when a specific time is reached.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'absolute' | No | No | Indicates that the absolute time-based expiration policy is used. |
| time | Date | No | No | Absolute time when a cache record expires. |
Defines the relative time-based expiration policy. A cache record expires after a specified period.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'relative' | No | No | Indicates that the relative time-based expiration policy is used. |
| time | TimeInterval | No | No | Period after which a cache record expires. |
Defines the sliding time window-based expiration policy. A cache record expires if it is not accessed within a specified time period. Each time it is accessed, its expiration timer is reset.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'sliding' | No | No | Indicates that the sliding time window-based expiration policy is used. |
| time | TimeInterval | No | No | Period after which a cache record expires. |
Defines time interval settings.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| units | TimeIntervalUnits | No | No | Time interval unit. |
| value | number | No | No | Time interval length. |
type TimeIntervalUnits = 'seconds' | 'minutes' | 'hours' | 'days'
Time interval unit.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Type | Description |
|---|---|
| 'seconds' | Time unit: second. |
| 'minutes' | Time unit: minute. |
| 'hours' | Time unit: hour. |
| 'days' | Time unit: day. |
Defines the information about HTTP response data stored in the cache.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| timeStamp | Date | No | No | Time when an HTTP response is obtained from the network. |
| originalRequestId | string | No | No | Original HTTP request ID. |
| statusCode | number | No | No | HTTP response status code. |
| headers | rcp.ResponseHeaders | No | No | HTTP response headers. |
| body | ArrayBuffer | No | Yes | HTTP response content. |
| effectiveUrl | string | No | Yes | Valid URL to which a request is redirected. The default value is undefined. |
| httpVersion | rcp.HttpVersion | No | Yes | HTTP version. |
| reasonPhrase | string | No | Yes | reasonPhrase of an HTTP status line, which provides a descriptive message associated with a numerical status code. |
| extra | ArrayBuffer | No | Yes | Additional information. Multiple response cache records to be stored for the same combination of a URL and an HTTP method. You can use this attribute to distinguish between them. For example, you can use this field to store a language type string to identify the response content of the corresponding language. |
Defines the key that identifies an HTTP response cache record.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| url | URLOrString | No | No | Request URL. |
| method | HttpMethod | No | No | HTTP method. |
| extra | string | No | Yes | Additional information. Multiple response cache records to be stored for the same combination of a URL and an HTTP method. You can use this attribute to distinguish between them. For example, you can use this field to store a language type string to identify the response content of the corresponding language. |
Defines the information of a cache record.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| expirationPolicy | ExpirationPolicy | No | No | Cache expiration policy. |
| response | CachedResponse | No | No | Cached response. |
| key | ResponseCacheKey | No | No | Cache key of the cached response. |
Defines cache configurations. You can call this API to control the cache behavior by performing configurations such as the memory and disk cache configuration, maximum cache size, maxim number of cache records, and default expiration policy type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| persistent | PersistentStorageConfiguration | No | No | Persistent cache configuration. |
| inMemory | InMemoryCacheConfiguration | No | Yes | Memory cache configuration. |
| maxItems | number | No | Yes | Maximum number of cache records for in-memory/persistent storage. When the parameter is set and the number of cache records exceeds this upper limit, an eviction policy based on the Least Recently Used (LRU) algorithm will be executed. It will first evict cache records that apply the time-constrained expiration policy, and then, if necessary, evict those applying the permanent expiration policy. |
| maxSize | number | No | Yes | Upper limit of in-memory/persistent storage. When the parameter is set and the cache size exceeds this upper limit, an eviction policy based on the Least Recently Used (LRU) algorithm will be executed. It will first evict cache records that apply the time-constrained expiration policy, and then, if necessary, evict those applying the permanent expiration policy. Unit: MB Default value: 50 |
| defaultExpirationPolicy | TimeLimitedExpirationPolicy | No | Yes | Default cache expiration policy. The specified cache expiration policy applies to each new response generated after it is set. If this attribute is not set, the SlidingTimeExpirationPolicy with the 1-hour time window will be used by default. The cache expiration policy specified using the set method will overwrite the default cache expiration policy specified by this API. |
type PersistentStorageConfiguration = FileSystemStorageConfiguration
Defines persistent cache storage configurations.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Type | Description |
|---|---|
| FileSystemStorageConfiguration | File system-based cache storage configurations. |
File system-based cache storage configurations.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| kind | 'file-system' | No | No | Persistent cache storage medium type. The key value is file-system, indicating file system-based medium storage. |
| pathToFolder | string | No | No | File path for cache storage. For details, please refer to Application Files. |
Defines in-memory cache storage configurations.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| maxItems | number | No | Yes | Maximum number of records in the in-memory cache. |
| maxSize | number | No | Yes | Maximum memory allocated for the in-memory cache. If this attribute is set, the maxSize attribute configured in CacheConfiguration does not take effect for the in-memory cache. Unit: MB Default value: 10 |
Defines cache status information, including the current number of cache records, cache size, and cache hit count.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| size | number | No | No | Number of bytes in the persistent cache storage. Unit: byte |
| count | number | No | No | Number of cache records in the persistent cache storage. |
| hitCount | number | No | No | Number of cache hits. |
Records and manages HTTP response caching. Remote Communication Kit does not encrypt cached HTTP responses. You can determine whether to use the HTTP response caching function based on your needs.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
constructor(configuration: CacheConfiguration)
Creates an HTTP response cache instance.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| configuration | CacheConfiguration | Yes | Cache settings. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
}); close(): Promise<void>
Closes the HTTP response cache instance and terminates all pending cache operations. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Returns:
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900985 | File system IO error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
await cache.close();
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} set(key: ResponseCacheKey, response: CachedResponse, expirationPolicy?: ExpirationPolicy): Promise<void>
Adds or replaces the cache content based on a cache key. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| key | ResponseCacheKey | Yes | Cache key. |
| response | CachedResponse | Yes | HTTP response cache content to be added or replaced with. |
| expirationPolicy | ExpirationPolicy | No | Defines the cache expiration policy types. The policy defined by this attribute will overwrite the default cache expiration policy (defaultExpirationPolicy) in CacheConfiguration. |
Returns:
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900401 | Parameter error. |
| 1007900985 | File system IO error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
const session: rcp.Session = rcp.createSession({
requestConfiguration: {
cache: cache
}
});
const key: rcp.ResponseCacheKey = {
url: 'https://www.example.com',
method: 'GET'
};
const response = await session.get('https://www.example.com');
const cachedRecord = rcp.createCachedResponse(response);
const policy: rcp.TimeLimitedExpirationPolicy = {
kind: 'relative',
time: {
units: 'seconds',
value: 3
}
};
await cache.set(key, cachedRecord, policy);
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} get(key: ResponseCacheKey): Promise<ResponseCacheRecord>
Obtains an HTTP response cache record based on the cache key. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| key | ResponseCacheKey | Yes | Cache key. |
Returns:
| Type | Description |
|---|---|
| Promise<ResponseCacheRecord> | Promise object, which returns the target HTTP response cache record. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900401 | Parameter error. |
| 1007900985 | File system IO error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
const record = await cache.get({
url: 'https://www.example.com',
method: 'GET'
});
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} clear(): Promise<void>
Clears the HTTP response cache. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Returns:
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900985 | File system IO error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
await cache.clear();
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} getState(): Promise<CacheState>
Obtains cache status information. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Returns:
| Type | Description |
|---|---|
| Promise<CacheState> | Promise object, which returns the cache status information. |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900985 | File system IO error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
const cacheState = await cache.getState();
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} remove(key: ResponseCacheKey): Promise<boolean>
Deletes an HTTP response cache record based on the specified cache key. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| key | ResponseCacheKey | Yes | Cache key. |
Returns:
| Type | Description |
|---|---|
| Promise<boolean> | Promise object, which returns either true (deletion successful) or false (deletion failed). |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900401 | Parameter error. |
| 1007900985 | File system IO error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
const key: rcp.ResponseCacheKey = {
url: 'https://www.example.com',
method: 'GET'
};
const result = await cache.remove(key);
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} removeMultiple(url: URLOrString, matchKind: URLMatchKind, method?: HttpMethod): Promise<boolean>
Searches for and then deletes one or more HTTP response cache records by URL matching. You can specify the URL matching type by setting matchKind. This API uses a promise to return the result.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| url | URLOrString | Yes | URL, which is used to match the URL in the cache key. |
| matchKind | URLMatchKind | Yes | URL matching type. |
| method | HttpMethod | No | HTTP request method. |
Returns:
| Type | Description |
|---|---|
| Promise<boolean> | Promise object, which returns either true (deletion successful) or false (deletion failed). |
Error codes:
For details about the error codes, please refer to API Error Codes.
| ID | Error Message |
|---|---|
| 1007900401 | Parameter error. |
| 1007900985 | File system IO error. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
const result = await cache.removeMultiple('https://www.example.com', 'exact', 'GET');
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} type URLMatchKind = 'exact' | 'as-substring'
URL matching type.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
| Type | Description |
|---|---|
| 'exact' | Exact URL matching. A URL can be matched only if it is exactly the same as the passed URL. |
| 'as-substring' | Substring URL matching. A URL can be matched if it contains the specified URL as a substring. |
createResponse(request: Request, cachedResponse: CachedResponse, currentTime: Date): Response
Creates an HTTP response based on the HTTP response cache record.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| request | Request | Yes | HTTP request for which a response needs to be created. |
| cachedResponse | CachedResponse | Yes | HTTP response cache record that is stored. |
| currentTime | Date | Yes | Current time. |
Returns:
| Type | Description |
|---|---|
| Response | HTTP response. |
Error codes:
For details about the error codes, please refer to API Error Codes.
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const cache = new rcp.ResponseCache({
persistent: {
kind: 'file-system',
pathToFolder: '/path/dir' // Set the path based on your service needs.
}
});
const request = new rcp.Request('https://www.example.com', 'GET');
const key: rcp.ResponseCacheKey = {
url: request.url,
method: request.method,
};
// Obtain the HTTP response cache result.
const responseInCache = await cache.get(key);
if (responseInCache) {
// Create an HTTP response based on the HTTP response cache record.
const response = rcp.createResponse(request, responseInCache.response, new Date());
}
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
} createCachedResponse(response: Response, timeStamp?: Date): CachedResponse
Creates an HTTP response cache record based on the HTTP response.
Model restriction: This API can be used only in the stage model.
System capability: SystemCapability.Collaboration.RemoteCommunication
Since: 6.0.0(20)
Parameters:
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| response | Response | Yes | HTTP response. |
| timeStamp | Date | No | Timestamp of the cached response. The current system time is used by default. |
Returns:
| Type | Description |
|---|---|
| CachedResponse | HTTP response cache. |
Example:
import { rcp } from '@kit.RemoteCommunicationKit';
try {
const session = rcp.createSession();
// Obtain the HTTP response.
const response = await session.get('https://www.example.com');
// Create an HTTP response cache record based on the HTTP response.
const cachedRecord = rcp.createCachedResponse(response);
console.info(`Succeeded in creating CachedResponse, result is ${JSON.stringify(cachedRecord)}`);
} catch (err) {
console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
}