本模块提供HTTP数据请求功能。应用程序可通过HTTP发起数据请求。常见的HTTP方法包括GET、POST、HEAD、PUT、DELETE、PATCH、OPTIONS等。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

## 导入模块

PhonePC/2in1TabletTVWearable



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
```

## createSession

PhonePC/2in1TabletTVWearable

createSession(sessionConfiguration?: SessionConfiguration): Session

创建HTTP会话。这是启动HTTP交互的主要方法。开发者可以使用此API与[SessionConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#sessionconfiguration)一起创建会话。

说明

自5.1.0(18)版本开始变更为最多可创建1024个session实例，应用在通过创建的session实例访问完网络请求后，应及时关闭session，保证资源合理利用。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| sessionConfiguration | [SessionConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#sessionconfiguration) | 否 | 会话配置，应用于会话请求的设置。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [Session](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#session) | 代表一个会话，用于发送HTTP请求并管理其配置、取消和关闭的生命周期。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/errorcode-universal#section401-参数检查失败) | Parameter error. |
| [1007900994](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900994-会话数达到限制) | Sessions number reached limit. |

**示例：**



```
1. const session = rcp.createSession();
```

## Session

PhonePC/2in1TabletTVWearable

Session类表示可用于发出HTTP请求的通信会话。它提供了各种HTTP方法（FETCH、GET、POST、PUT、HEAD、DELETE、CANCEL、CLOSE）。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

### 属性

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| id | string | 是 | 否 | 表示会话的标识符。 |
| configuration | [SessionConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#sessionconfiguration) | undefined | 是 | 否 | 表示会话的配置设置。 |

### fetch

PhonePC/2in1TabletTVWearable

fetch(request: Request): Promise<Response>

发送一个HTTP请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 是 | 要发送的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. let req = new rcp.Request("http://example.com/fetch", "POST");
6. session.fetch(req).then((response) => {
7. console.info(`Succeeded in getting the response ${response}`);
8. }).catch((err: BusinessError) => {
9. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
10. });
```

### fetchForSendable

PhonePC/2in1TabletTVWearable

fetchForSendable(request: Request): Promise<ResponseSendable>

发送一个HTTP请求，并返回服务器的HTTP响应，该响应消息支持Sendable。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 是 | 待发送的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[ResponseSendable](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsesendable)> | Promise对象，返回来自服务器的响应对象，该响应对象支持Sendable。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { ArkTSUtils, collections, taskpool, util } from '@kit.ArkTS';

4. @Concurrent
5. async function taskFunc(sendableResponse: rcp.ResponseSendable) {
6. console.info(`sendableResponse: ${ArkTSUtils.ASON.stringify(sendableResponse)}`);
7. // 打印Sendable类型的body数据
8. if (ArkTSUtils.isSendable(sendableResponse.body) && sendableResponse.body != undefined) {
9. const decoder = util.TextDecoder.create('utf-8');
10. let arr: collections.Uint8Array = new collections.Uint8Array(sendableResponse.body);
11. let str = decoder.decodeToString(arr as Object as Uint8Array).trim();
12. console.info(`body:${ArkTSUtils.ASON.stringify(str)}`);
13. }
14. }

16. async function test() {
17. try {
18. const session = rcp.createSession();
19. let request = new rcp.Request('https://www.example.com'); // 请在使用中将其替换为真实的网址。
20. let sendableResponse = await session.fetchForSendable(request);
21. let isSendable = ArkTSUtils.isSendable(sendableResponse);
22. if (isSendable) {
23. console.info(`Succeeded in getting the response, the response is sendable`);
24. } else {
25. console.info(`Succeeded in getting the response, the response is not sendable`);
26. }
27. let task: taskpool.Task = new taskpool.Task(taskFunc, sendableResponse);
28. await taskpool.execute(task);
29. } catch (err) {
30. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
31. }
32. }
```

### get

PhonePC/2in1TabletTVWearable

get(url: URLOrString, destination?: ResponseBodyDestination): Promise<Response>

发送一个带有默认HTTP参数的HTTP GET请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP GET请求资源的URL。 |
| destination | [ResponseBodyDestination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsebodydestination) | 否 | HTTP响应的目标位置或目的地。  **起始版本：** 5.0.0(12) |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. session.get("http://example.com/get").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### post

PhonePC/2in1TabletTVWearable

post(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>

发送一个带有默认HTTP参数的HTTP POST请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP POST请求资源的URL。 |
| content | [RequestContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontent) | 否 | 请求的正文内容。默认为undefined。 |
| destination | [ResponseBodyDestination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsebodydestination) | 否 | HTTP响应的目标位置或目的地。  **起始版本：** 5.0.0(12) |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. session.post("http://example.com/post", "data to send").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### put

PhonePC/2in1TabletTVWearable

put(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>

发送一个带有默认HTTP参数的HTTP PUT请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP PUT请求资源的URL。 |
| content | [RequestContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontent) | 否 | 请求正文发送的内容。默认为undefined。 |
| destination | [ResponseBodyDestination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsebodydestination) | 否 | HTTP响应的目标位置或目的地。  **起始版本：** 5.0.0(12) |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. session.put("http://example.com/put", "data to send").then((response) => {
6. console.info(`Succeeded in getting the response ${response.toString()}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### downloadToFile

PhonePC/2in1TabletTVWearable

downloadToFile(url: URLOrString, downloadTo: DownloadToFile): Promise<Response>

发送一个带有默认HTTP参数的HTTP DOWNLOADTOFILE请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP DOWNLOADTOFILE请求资源的URL。 |
| downloadTo | [DownloadToFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtofile) | 是 | HTTP中用于将服务器上下载的文件保存到本地文件系统中的指定位置。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. let downloadToFile: rcp.DownloadToFile = {
5. kind: 'folder',
6. path: "/path/dir" // 请根据自身业务选择合适的路径
7. } as rcp.DownloadToFile
8. const session = rcp.createSession();
9. session.downloadToFile("http://www.example.com", downloadToFile).then((response) => {
10. console.info(`Succeeded in getting the response ${response.toString()}`);
11. }).catch((err: BusinessError) => {
12. console.error(`DownloadToFile failed, the error code is ${err.code}, error data is ${err.data}`);
13. });
```

### uploadFromFile

PhonePC/2in1TabletTVWearable

uploadFromFile(url: URLOrString, uploadFrom: UploadFromFile): Promise<Response>

发送一个带有默认HTTP参数的HTTP UPLOADFROMFILE请求，完成上传文件功能，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP UPLOADFROMFILE请求资源的URL。 |
| uploadFrom | [UploadFromFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#uploadfromfile) | 是 | HTTP中从本地计算机上传文件到服务器的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. let fileDir = "/path/dir/"; // 请根据自身业务定义此路径
5. let uploadFromFile: rcp.UploadFromFile = {
6. fileOrPath: fileDir
7. };
8. const session = rcp.createSession();
9. session.uploadFromFile("http://example.com/head", uploadFromFile).then((response) => {
10. console.info(`Succeeded in getting the response ${response.toString()}`);
11. }).catch((err: BusinessError) => {
12. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
13. });
```

### downloadToStream

PhonePC/2in1TabletTVWearable

downloadToStream(url: URLOrString, downloadTo: DownloadToStream): Promise<Response>

发起一个带默认HTTP参数的流式下载（DOWNLOADTOSTREAM）请求，从服务器下载数据流，并返回HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP DOWNLOADTOSTREAM请求资源的URL。 |
| downloadTo | [DownloadToStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtostream-2) | 是 | HTTP中将请求文件从服务器下载到客户端，并将其写入到一个数据流中。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit'

4. const streamData: rcp.WriteStream = {
5. write(buffer: ArrayBuffer): Promise<void | number> {
6. return Promise.resolve(buffer.byteLength)
7. }
8. };

10. let downloadToStream: rcp.DownloadToStream = {
11. kind: 'stream',
12. stream: streamData
13. }
14. const session = rcp.createSession();
15. session.downloadToStream("http://example.com/head", downloadToStream).then((response) => {
16. console.info(`Succeeded in getting the response ${response}`);
17. }).catch((err: BusinessError) => {
18. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
19. });
```

### uploadFromStream

PhonePC/2in1TabletTVWearable

uploadFromStream(url: URLOrString, uploadFrom: UploadFromStream): Promise<Response>

发起一个带默认HTTP参数的流式上传（UPLOADFROMSTREAM）请求，将数据流上传至服务器，并返回HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP UPLOADFROMSTREAM请求资源的URL。 |
| uploadFrom | [UploadFromStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#uploadfromstream-2) | 是 | HTTP中从一个输入流中上传数据到服务器的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. let uploadFromStream: rcp.UploadFromStream = {
5. stream: object // 此处请自行定义类型为Stream、ReadStream、SyncReadStream的对象
6. }
7. const session = rcp.createSession();
8. session.uploadFromStream("http://example.com/head", uploadFromStream).then((response) => {
9. console.info(`Succeeded in getting the response ${response}`);
10. }).catch((err: BusinessError) => {
11. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
12. });
```

### head

PhonePC/2in1TabletTVWearable

head(url: URLOrString): Promise<Response>

发送一个带有默认HTTP参数的HTTP HEAD请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP HEAD请求资源的URL。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. session.head("http://example.com/head").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### delete

PhonePC/2in1TabletTVWearable

delete(url: URLOrString): Promise<Response>

发送一个带有默认HTTP参数的HTTP DELETE请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP DELETE请求资源的URL。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. session.delete("http://example.com/delete").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### cancel

PhonePC/2in1TabletTVWearable

cancel(requestToCancel?: Request | Request[]): void

取消指定或正在进行的会话请求。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| requestToCancel | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request)[] | 否 | 要取消的请求或请求数组。在不指定[Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request)情况下，默认取消所有请求。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/errorcode-universal#section401-参数检查失败) | Parameter error. |

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. let req = new rcp.Request("http://example.com/fetch", "GET");
6. session.fetch(req).then((response) => {
7. console.info(`Succeeded in getting the response ${response}`);
8. session.cancel(req);
9. }).catch((err: BusinessError) => {
10. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
11. });
```

### close

PhonePC/2in1TabletTVWearable

close(): void

关闭会话。调用此方法以释放与此会话关联的资源。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. let req = new rcp.Request("http://example.com/fetch", "GET");
6. session.fetch(req).then((response) => {
7. console.info(`Succeeded in getting the response ${response}`);
8. session.close();
9. }).catch((err: BusinessError) => {
10. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
11. session.close();
12. });
```

## getDefaultSession

PhonePC/2in1TabletTVWearable

getDefaultSession(): DefaultSession

获取默认的HTTP会话。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [DefaultSession](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#defaultsession) | 代表一个默认会话，用于发送或取消HTTP请求。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const defaultSession = rcp.getDefaultSession();
```

## DefaultSession

PhonePC/2in1TabletTVWearable

DefaultSession类表示一个默认的通信会话，可用于发送HTTP请求。如果不需要定制Session的配置，可以使用DefaultSession便捷地发起网络请求。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

### fetch

PhonePC/2in1TabletTVWearable

fetch(request: Request): Promise<Response>

发送一个HTTP请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 是 | 要发送的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const defaultSession = rcp.getDefaultSession();
5. let req = new rcp.Request("http://example.com/fetch", "POST");
6. defaultSession.fetch(req).then((response) => {
7. console.info(`Succeeded in getting the response ${response}`);
8. }).catch((err: BusinessError) => {
9. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
10. });
```

### fetchForSendable

PhonePC/2in1TabletTVWearable

fetchForSendable(request: Request): Promise<ResponseSendable>

发送一个HTTP请求，并返回服务器的HTTP响应，该响应消息支持Sendable。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 是 | 待发送的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[ResponseSendable](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsesendable)> | Promise对象，返回来自服务器的响应对象，该响应对象支持Sendable。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { ArkTSUtils, collections, taskpool, util } from '@kit.ArkTS';

4. @Concurrent
5. async function taskFunc(sendableResponse: rcp.ResponseSendable) {
6. console.info(`sendableResponse: ${ArkTSUtils.ASON.stringify(sendableResponse)}`);
7. // 打印Sendable类型的body数据
8. if (ArkTSUtils.isSendable(sendableResponse.body) && sendableResponse.body != undefined) {
9. const decoder = util.TextDecoder.create('utf-8');
10. let arr: collections.Uint8Array = new collections.Uint8Array(sendableResponse.body);
11. let str = decoder.decodeToString(arr as Object as Uint8Array).trim();
12. console.info(`body:${ArkTSUtils.ASON.stringify(str)}`);
13. }
14. }

16. async function test() {
17. try {
18. const defaultSession = rcp.getDefaultSession();
19. let request = new rcp.Request('https://www.example.com'); // 请在使用中将其替换为真实的网址。
20. let sendableResponse = await defaultSession.fetchForSendable(request);
21. let isSendable = ArkTSUtils.isSendable(sendableResponse);
22. if (isSendable) {
23. console.info(`Succeeded in getting the response, the response is sendable`);
24. } else {
25. console.info(`Succeeded in getting the response, the response is not sendable`);
26. }
27. let task: taskpool.Task = new taskpool.Task(taskFunc, sendableResponse);
28. await taskpool.execute(task);
29. } catch (err) {
30. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
31. }
32. }
```

### get

PhonePC/2in1TabletTVWearable

get(url: URLOrString, destination?: ResponseBodyDestination): Promise<Response>

发送一个带有默认HTTP参数的HTTP GET请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP GET请求资源的URL。 |
| destination | [ResponseBodyDestination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsebodydestination) | 否 | HTTP响应的目标位置或目的地。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const defaultSession = rcp.getDefaultSession();
5. defaultSession.get("http://example.com/get").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### post

PhonePC/2in1TabletTVWearable

post(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>

发送一个带有默认HTTP参数的HTTP POST请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP POST请求资源的URL。 |
| content | [RequestContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontent) | 否 | 请求的正文内容。默认为undefined。 |
| destination | [ResponseBodyDestination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsebodydestination) | 否 | HTTP响应的目标位置或目的地。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const defaultSession = rcp.getDefaultSession();
5. defaultSession.post("http://example.com/post", "data to send").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### put

PhonePC/2in1TabletTVWearable

put(url: URLOrString, content?: RequestContent, destination?: ResponseBodyDestination): Promise<Response>

发送一个带有默认HTTP参数的HTTP PUT请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP PUT请求资源的URL。 |
| content | [RequestContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontent) | 否 | 请求正文发送的内容。默认为undefined。 |
| destination | [ResponseBodyDestination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsebodydestination) | 否 | HTTP响应的目标位置或目的地。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const defaultSession = rcp.getDefaultSession();
5. defaultSession.put("http://example.com/put", "data to send").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### downloadToFile

PhonePC/2in1TabletTVWearable

downloadToFile(url: URLOrString, downloadTo: DownloadToFile): Promise<Response>

发送一个带有默认HTTP参数的HTTP DOWNLOADTOFILE请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP DOWNLOADTOFILE请求资源的URL。 |
| downloadTo | [DownloadToFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtofile) | 是 | HTTP中用于将服务器上下载的文件保存到本地文件系统中的指定位置。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. let downloadToFile: rcp.DownloadToFile = {
5. kind: 'folder',
6. path: "/path/dir" // 请根据自身业务选择合适的路径
7. } as rcp.DownloadToFile
8. const defaultSession = rcp.getDefaultSession();
9. defaultSession.downloadToFile("http://www.example.com", downloadToFile).then((response) => {
10. console.info(`Succeeded in getting the response ${response}`);
11. }).catch((err: BusinessError) => {
12. console.error(`DownloadToFile failed, the error code is ${err.code}, error data is ${err.data}`);
13. });
```

### uploadFromFile

PhonePC/2in1TabletTVWearable

uploadFromFile(url: URLOrString, uploadFrom: UploadFromFile): Promise<Response>

发送一个带有默认HTTP参数的HTTP UPLOADFROMFILE请求，完成上传文件功能，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP UPLOADFROMFILE请求资源的URL。 |
| uploadFrom | [UploadFromFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#uploadfromfile) | 是 | HTTP中从本地计算机上传文件到服务器的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. let fileDir = "/path/dir/"; // 请根据自身业务定义此路径
5. let uploadFromFile: rcp.UploadFromFile = {
6. fileOrPath: fileDir
7. };
8. const defaultSession = rcp.getDefaultSession();
9. defaultSession.uploadFromFile("http://example.com/head", uploadFromFile).then((response) => {
10. console.info(`Succeeded in getting the response ${response}`);
11. }).catch((err: BusinessError) => {
12. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
13. });
```

### downloadToStream

PhonePC/2in1TabletTVWearable

downloadToStream(url: URLOrString, downloadTo: DownloadToStream): Promise<Response>

发起一个带默认HTTP参数的流式下载（DOWNLOADTOSTREAM）请求，从服务器下载数据流，并返回HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP DOWNLOADTOSTREAM请求资源的URL。 |
| downloadTo | [DownloadToStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtostream) | 是 | HTTP中将请求文件从服务器下载到客户端，并将其写入到一个数据流中。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit'

4. const streamData: rcp.WriteStream = {
5. write(buffer: ArrayBuffer): Promise<void | number> {
6. return Promise.resolve(buffer.byteLength)
7. }
8. };

10. let downloadToStream: rcp.DownloadToStream = {
11. kind: 'stream',
12. stream: streamData
13. }
14. const defaultSession = rcp.getDefaultSession();
15. defaultSession.downloadToStream("http://example.com/head", downloadToStream).then((response) => {
16. console.info(`Succeeded in getting the response ${response}`);
17. }).catch((err: BusinessError) => {
18. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
19. });
```

### uploadFromStream

PhonePC/2in1TabletTVWearable

uploadFromStream(url: URLOrString, uploadFrom: UploadFromStream): Promise<Response>

发起一个带默认HTTP参数的流式上传（UPLOADFROMSTREAM）请求，将数据流上传至服务器，并返回HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP UPLOADFROMSTREAM请求资源的URL。 |
| uploadFrom | [UploadFromStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#uploadfromstream) | 是 | HTTP中从一个输入流中上传数据到服务器的请求。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. let uploadFromStream: rcp.UploadFromStream = {
5. stream: object // 此处请自行定义类型为Stream、ReadStream、SyncReadStream的对象
6. }
7. const defaultSession = rcp.getDefaultSession();
8. defaultSession.uploadFromStream("http://example.com/head", uploadFromStream).then((response) => {
9. console.info(`Succeeded in getting the response ${response}`);
10. }).catch((err: BusinessError) => {
11. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
12. });
```

### head

PhonePC/2in1TabletTVWearable

head(url: URLOrString): Promise<Response>

发送一个带有默认HTTP参数的HTTP HEAD请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP HEAD请求资源的URL。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const defaultSession = rcp.getDefaultSession();
5. defaultSession.head("http://example.com/head").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### delete

PhonePC/2in1TabletTVWearable

delete(url: URLOrString): Promise<Response>

发送一个带有默认HTTP参数的HTTP DELETE请求，并返回来自服务器的HTTP响应。使用Promise异步回调。

**需要权限：** ohos.permission.INTERNET（如果使用[PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference)的'cellular'模式，则额外需要ohos.permission.GET\_NETWORK\_INFO）

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | HTTP DELETE请求资源的URL。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const defaultSession = rcp.getDefaultSession();
5. defaultSession.delete("http://example.com/delete").then((response) => {
6. console.info(`Succeeded in getting the response ${response}`);
7. }).catch((err: BusinessError) => {
8. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
9. });
```

### cancel

PhonePC/2in1TabletTVWearable

cancel(requestToCancel?: Request | Request[]): void

取消指定或正在进行的会话请求。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| requestToCancel | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request)[] | 否 | 要取消的请求或请求数组。在不指定[Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request)情况下，默认取消所有请求。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const defaultSession = rcp.getDefaultSession();
5. let req = new rcp.Request("http://example.com/fetch", "GET");
6. defaultSession.fetch(req).then((response) => {
7. console.info(`Succeeded in getting the response ${response}`);
8. defaultSession.cancel(req);
9. }).catch((err: BusinessError) => {
10. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
11. });
```

## RequestHandler

PhonePC/2in1TabletTVWearable

拦截器的请求处理器。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### handle

PhonePC/2in1TabletTVWearable

handle(context: RequestContext): Promise<Response>

远场通信框架会预置两种处理器，一种会调用拦截器的[intercept](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#intercept)函数，一种会调用系统的fetchInternal使用系统能力发起请求，使用promise异步回调。

比如，拦截器：[A, B, C, D]会被构造成：

A {handler->B{handler->C{handler-D{handler->系统能力}}}}

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| context | [RequestContext](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontext) | 是 | 请求上下文 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象，返回来自服务器的响应对象。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. class RequestHandler implements rcp.RequestHandler {
4. handle(context: rcp.RequestContext): Promise<rcp.Response> {
5. let handlerRequest = new rcp.Request("https://www.example.com", 'GET');
6. let handlerSession = rcp.createSession();
7. context.request = handlerRequest;
8. context.session = handlerSession;
9. return new Promise<rcp.Response>((resolve, reject) => {
10. handlerSession.get("https://www.example.com").then((response: rcp.Response) => {
11. resolve(response);
12. }).catch((error: Error) => {
13. reject(error);
14. })
15. });
16. }
17. }
```

## RequestContext

PhonePC/2in1TabletTVWearable

拦截器请求上下文。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 否 | HTTP请求 |
| session | [Session](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#session) | 否 | 否 | 持有此拦截器的会话 |

## Interceptor

PhonePC/2in1TabletTVWearable

拦截器。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### intercept

PhonePC/2in1TabletTVWearable

intercept(context: RequestContext, next: RequestHandler): Promise<Response>

拦截器，用于修改请求、修改响应或者直接返回响应，使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| context | [RequestContext](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontext) | 是 | 请求上下文 |
| next | [RequestHandler](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requesthandler) | 是 | 下一个请求处理器 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)> | Promise对象。此拦截器对下一个拦截器做拦截、修改、透传等操作后，返回此拦截器提供的[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)对象。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';

4. class ResponseCache {
5. private readonly cache: Record<string, rcp.Response> = {};

7. getResponse(url: string): rcp.Response {
8. return this.cache[url];
9. }

11. setResponse(url: string, response: rcp.Response): void {
12. this.cache[url] = response;
13. }
14. }

16. class ResponseCachingInterceptor implements rcp.Interceptor {
17. private readonly cache: ResponseCache;

19. constructor(cache: ResponseCache) {
20. this.cache = cache;
21. }

23. async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
24. const url = context.request.url.href;
25. const responseFromCache = this.cache.getResponse(url);
26. if (responseFromCache) {
27. return Promise.resolve(responseFromCache);
28. }
29. const promise = next.handle(context);
30. promise.then((resp) => {
31. resp.statusCode;
32. cache.setResponse(url, resp);
33. });
34. return promise;
35. }
36. }

38. const cache = new ResponseCache();

40. function testInterceptor() {
41. const session = rcp.createSession({
42. interceptors: [new ResponseCachingInterceptor(cache)]
43. });

45. session.get('https://www.example.com').then((response: rcp.Response) => {
46. console.info(`Response succeeded. The statusCode of the response is ${response.statusCode}`);
47. }).catch((err: BusinessError) => {
48. console.error(`Response failed: error code is ${err.code}, error data is ${err.data}`);
49. });

51. let request = new rcp.Request("https://www.example.com", 'GET');
52. session.fetch(request).then((response: rcp.Response) => {
53. console.info(`Response succeeded. The statusCode of the response is ${response.statusCode}`);
54. }).catch((err: BusinessError) => {
55. console.error(`Response failed: error code is ${err.code}, error data is ${err.data}`);
56. });
57. }
```

## SessionConfiguration

PhonePC/2in1TabletTVWearable

SessionConfiguration接口定义了会话的配置参数，为开发者提供了对HTTP会话各个方面的详细控制。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| interceptors | [Interceptor](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#interceptor)[] | 否 | 是 | 请求/响应拦截器。  **起始版本：** 5.0.0(12) |
| requestConfiguration | [Configuration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#configuration) | 否 | 是 | 指定与会话关联的HTTP请求的配置。包括transfer、proxy、DNS、connection和security configurations。 |
| baseAddress | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 否 | 是 | 设置会话中URL的基地址。这允许开发者为会话中的多个请求定义一个通用的基本URL。如果请求URL不是绝对URL，则把基地址预制在请求URL的前面。例如，"https://example.com?name=value"，"https://example.com"为基地址，"?name=value"为请求URL。 |
| headers | [RequestHeaders](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestheaders) | 否 | 是 | 为Session发出的HTTP请求定义headers（可自定义）。开发者可以根据他们的需求定制的特定headers。 |
| cookies | [RequestCookies](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcookies) | 否 | 是 | 提供在与会话关联的HTTP请求中包含自定义cookie的方法。适用于需要将某些cookie附加到每个请求的场景。需要手动设置cookie，携带cookie为用户行为。 |
| sessionListener | [SessionListener](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#sessionlistener) | 否 | 是 | 允许开发者将侦听器附加到会话，接收会话取消或关闭等事件的通知，更好地处理应用程序中与会话相关的事件。 |
| connectionConfiguration | [ConnectionConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#connectionconfiguration) | 否 | 是 | 连接配置。用于指定此会话中允许的并发TCP连接总数以及单个主机所允许的最大并发TCP 连接数。  **起始版本：** 5.0.0(12) |
| cacheControl | [CacheControl](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cachecontrol) | 否 | 是 | 缓存控制配置。用于主动控制会话中缓存验证策略，影响服务器或中间代理如何响应请求。  **起始版本：** 6.0.0(20) |
| cookieRepository | [CookieRepository](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cookierepository) | 否 | 是 | cookie仓库。会话中的所有请求会共享cookie仓库。如果配置此项，那么此[Session](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#session)上的请求实际上都会由[DefaultSession](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#defaultsession)处理。  **起始版本：** 6.1.0(23) |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. let cookieRepository = rcp.CookieRepository.create();
4. const sessionConfig: rcp.SessionConfiguration = {
5. requestConfiguration: {
6. transfer: {
7. autoRedirect: true,
8. timeout: {
9. connectMs: 5000,
10. transferMs: 10000
11. }
12. },
13. tracing: {
14. verbose: true
15. }
16. },
17. baseAddress: "http://api.example.com",
18. headers: {
19. "Authorization": "Bearer YOUR_ACCESS_TOKEN",
20. "Content-Type": "application/json"
21. },
22. cookies: {
23. "user": "john_doe",
24. "session_id": "abc123"
25. },
26. sessionListener: {
27. onCanceled: () => console.info("Session was cancelled"),
28. onClosed: () => console.info("Session was closed")
29. },
30. cookieRepository: cookieRepository,
31. // ...
32. };

34. const session = rcp.createSession(sessionConfig);
```

**interceptors属性示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';

4. class ResponseCache {
5. private readonly cache: Record<string, rcp.Response> = {};

7. getResponse(url: string): rcp.Response {
8. return this.cache[url];
9. }

11. setResponse(url: string, response: rcp.Response): void {
12. this.cache[url] = response;
13. }
14. }

16. class ResponseCachingInterceptor implements rcp.Interceptor {
17. private readonly cache: ResponseCache;

19. constructor(cache: ResponseCache) {
20. this.cache = cache;
21. }

23. async intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> {
24. const url = context.request.url.href;
25. const responseFromCache = this.cache.getResponse(url);
26. if (responseFromCache) {
27. return Promise.resolve(responseFromCache);
28. }
29. const promise = next.handle(context);
30. promise.then((resp) => {
31. this.cache.setResponse(url, resp);
32. });
33. return promise;
34. }
35. }

37. const cache = new ResponseCache();

39. function testInterceptor() {
40. const session = rcp.createSession({
41. interceptors: [new ResponseCachingInterceptor(cache)]
42. });

44. session.get('https://www.example.com').then((response: rcp.Response) => {
45. console.info(`Response succeeded. The statusCode of the response is ${response.statusCode}`);
46. }).catch((err: BusinessError) => {
47. console.error(`Response failed: error code is ${err.code}, error data is ${err.data}`);
48. });

50. let request = new rcp.Request("https://www.example.com", 'GET');
51. session.fetch(request).then((response: rcp.Response) => {
52. console.info(`Response succeeded. The statusCode of the response is ${response.statusCode}`);
53. }).catch((err: BusinessError) => {
54. console.error(`Response failed: error code is ${err.code}, error data is ${err.data}`);
55. });
56. }
```

## Configuration

PhonePC/2in1TabletTVWearable

Configuration接口包含一组配置参数，开发者可以利用这些参数来微调会话中HTTP请求的行为。这包括传输、跟踪、代理、DNS和安全配置的设置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| transfer | [TransferConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#transferconfiguration) | 否 | 是 | 配置与HTTP请求期间的数据传输相关的各个方面，例如自动重定向和超时设置。 |
| tracing | [TracingConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tracingconfiguration) | 否 | 是 | 使开发者能够在HTTP请求期间捕获详细的跟踪信息，有助于调试和性能分析。 |
| proxy | [ProxyConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#proxyconfiguration) | 否 | 是 | 配置会话的代理设置，允许开发者定义'system'、'no-proxy'或WebProxy配置。 |
| dns | [DnsConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#dnsconfiguration) | 否 | 是 | 指定与DNS相关的配置，包括自定义DNS规则和通过HTTPS使用DNS的选项。 |
| security | [SecurityConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#securityconfiguration) | 否 | 是 | 包括用于处理安全相关方面的设置，如证书和服务器身份验证。 |
| processing | [ProcessingConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#processingconfiguration) | 否 | 是 | 响应处理配置。  **起始版本：** 5.0.0(12) |
| cache | [ResponseCache](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecache) | 否 | 是 | 指定与HTTP缓存相关的配置。  **起始版本：** 6.0.0(20) |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const cache: rcp.ResponseCache = new rcp.ResponseCache({
4. persistent: {
5. kind: 'file-system',
6. pathToFolder: "/path/dir/" // 请根据自身业务指定缓存路径
7. }
8. });
9. const requestConfig: rcp.Configuration = {
10. transfer: {
11. autoRedirect: true,
12. timeout: {
13. connectMs: 5000,
14. transferMs: 10000
15. },
16. assumesHTTP3Capable: true,
17. pathPreference: "cellular"
18. },
19. tracing: {
20. verbose: true
21. },
22. proxy: "system",
23. dns: {
24. dnsRules: [
25. { host: "https://example.com", port: 443, ipAddresses: ["192.168.1.1", "192.168.1.2"] }
26. ]
27. },

29. security: {
30. certificate: {
31. content: "-----BEGIN CERTIFICATE-----\n...",
32. type: "PEM",
33. key: "/path/dir/", // 请根据自身业务对key进行修改
34. keyPassword: "your-password"
35. },
36. serverAuthentication: {
37. credential: {
38. username: "your-username",
39. password: "your-password"
40. },
41. authenticationType: "basic"
42. }
43. },
44. cache: cache
45. };

47. // Use the configuration in the session creation
48. const session = rcp.createSession({ requestConfiguration: requestConfig });
```

## ConnectionConfiguration

PhonePC/2in1TabletTVWearable

ConnectionConfiguration接口包含两个参数，开发者可以调整最大并发TCP的连接数也可以对单个主机或此次会话中的TCP最大连接数进行调整。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| maxConnectionsPerHost | number | 是 | 是 | 单个主机允许的最大并发 TCP 连接数（主机与主机名+端口号对相同）。  取值范围：1~2147483647。  默认值：6。 |
| maxTotalConnections | number | 是 | 是 | 此会话中允许的最大同时 TCP 连接总数。  取值范围：1~2147483647。  默认值为 64。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit'

3. const connectionConfig: rcp.ConnectionConfiguration = {
4. maxConnectionsPerHost: 6,
5. maxTotalConnections: 64
6. }
7. const session = rcp.createSession({ connectionConfiguration: connectionConfig });
```

## TcpConfiguration

PhonePC/2in1TabletTVWearable

TcpConfiguration接口为开发者提供设置TCP选项的能力。

当keepIdleSec、keepCnt、keepIntervalSec三个参数中至少有一个设置时，客户端会主动发送探测报文，未设置的参数将使用本文档中规定的默认值。若服务器一直不回复探测报文，TCP连接将在keepIdleSec + (keepCnt + 1) \* keepIntervalSec秒后断开。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| keepIdleSec | number | 否 | 是 | 该参数设置一个计时器，TCP连接将在计时器触发时发送探测报文。  单位：s。  取值范围：1~7200。  默认值：7200。 |
| userTimeoutMs | number | 否 | 是 | 该参数设置一个超时时间。若传输的数据在超时时间内未收到服务器的确认报文，TCP连接将被断开。  单位：ms。  取值范围：1~3600000。  默认值：和[Timeout](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeout).transferMs保持一致。 |
| keepCnt | number | 否 | 是 | 该参数设置发送探测报文的次数。  单位：次。  取值范围：1~9。  默认值：9。 |
| keepIntervalSec | number | 否 | 是 | 该参数设置每个探测报文之间的时间间隔。  单位：s。  取值范围：1~75。  默认值：75。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const transferConfig: rcp.TransferConfiguration = {
4. tcp: {
5. keepIdleSec: 20,
6. userTimeoutMs: 3000,
7. keepCnt: 6,
8. keepIntervalSec: 30,
9. }
10. };

12. // Use the configuration in the session creation.
13. const session = rcp.createSession({
14. requestConfiguration: {
15. transfer: transferConfig
16. }
17. });

19. // Use the configuration in the request.
20. const request = new rcp.Request('https://example.com');
21. request.configuration = {
22. transfer: transferConfig
23. };
```

## CookieRepository

PhonePC/2in1TabletTVWearable

cookie仓库。cookie仓库能够自动存储HTTP响应中的cookie，自动在HTTP请求中携带cookie，也支持手动管理仓库中的cookie。cookie仓库约每30秒将现有的cookie存储到本地，也可以使用[setCookies](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#setcookies)主动将cookie存储到本地。使用cookie仓库的[Session](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#session)实际上都会通过[DefaultSession](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#defaultsession)处理请求。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

### create

PhonePC/2in1TabletTVWearable

static create(identifier?: string): CookieRepository

创建cookie仓库。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| identifier | string | 否 | cookie仓库标识。只能包含大写字母、小写字母和下划线。  传入undefined、null或空字符串时默认为'default'。  传入其他字符时抛出[1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误)错误。  具有同样标识的cookie仓库共享cookie信息（即具有同样标识的cookie仓库实例使用起来如同同一个实例）。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [CookieRepository](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cookierepository) | cookie仓库实例。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误) | Parameter error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. rcp.CookieRepository.create('myRepo');
5. } catch (err) {
6. console.error(`create error, error code is ${err.code}, error data is ${err.data}`);
7. }
```

### setCookies

PhonePC/2in1TabletTVWearable

setCookies(cookies: ResponseCookie | ResponseCookie[]): Promise<void>

添加或修改cookie，并将cookie仓库中现有的cookie存储到本地。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| cookies | [ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie) | [ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie)[] | 是 | 传入cookie仓库的cookie。cookie仓库里实际会存如下7项数据：domain、httpOnly、path、isSecure、expires、name和value。当两个cookie的name、domain、path三项完全相同时，视为同一个cookie。  path默认为'/'。  domain不设置或者设置为空字符串时抛出[1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误)错误。  maxAge会转化为expires。maxAge和expires都设置时，使用maxAge。  expires应是符合[RFC 7231](https://www.rfc-editor.org/rfc/rfc7231.html)协议，并且是GMT时间的字符串，精确到秒，例如：'Wed, 21 Oct 2025 07:28:00 GMT'。当expires字段传入无效字符串时抛出[1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误)错误。  系统会不定期清除expires过期的cookie。传入空数组时，仅将cookie仓库中现有的cookie存储到本地。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void> | Promise对象，无返回结果。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误) | Parameter error. |
| [1007900999](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900999-内部错误) | Internal Error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';

4. let cookieRepository = rcp.CookieRepository.create('myRepo');
5. let cookie: rcp.ResponseCookie = {
6. name:'session_1',
7. value:'10001',
8. domain:'www.example.com', // 域名请根据实际业务配置
9. maxAge: 60,
10. isSecure: true
11. }
12. cookieRepository.setCookies(cookie).then(() => {
13. console.info('setCookies success.');
14. }).catch((err: BusinessError) => {
15. console.error(`setCookies error, error code is ${err.code}, error data is ${err.data}`);
16. })
```

### getAllCookies

PhonePC/2in1TabletTVWearable

getAllCookies(): Promise<ResponseCookie[]>

查询cookie仓库中所有的cookie。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie)[]> | Promise对象，返回[ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie)列表。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900999](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900999-内部错误) | Internal Error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';

4. let cookieRepository = rcp.CookieRepository.create('myRepo');
5. cookieRepository.getAllCookies().then((cookies) => {
6. console.info(`cookies num: ${cookies.length}`);
7. }).catch((err: BusinessError) => {
8. console.error(`getAllCookies error, error code is ${err.code}, error data is ${err.data}`);
9. })
```

### getCookiesByUrl

PhonePC/2in1TabletTVWearable

getCookiesByUrl(url: URL): Promise<ResponseCookie[]>

根据url从cookie仓库获取cookie。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URL](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#url) | 是 | HTTP请求的url，用于匹配cookie。匹配规则符合[RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265)协议。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie)[]> | Promise对象，返回匹配url的cookie列表。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900999](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900999-内部错误) | Internal Error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';
3. import { url } from '@kit.ArkTS';

5. let cookieRepository = rcp.CookieRepository.create('myRepo');
6. cookieRepository.getCookiesByUrl(url.URL.parseURL('https://www.example.com')).then((cookies) => {
7. console.info(`cookies num: ${cookies.length}`);
8. }).catch((err: BusinessError) => {
9. console.error(`getCookiesByUrl error, error code is ${err.code}, error data is ${err.data}`);
10. })
```

### deleteCookies

PhonePC/2in1TabletTVWearable

deleteCookies(cookies?: ResponseCookie | ResponseCookie[]): Promise<void>

删除指定的cookie。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| cookies | [ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie) | [ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie)[] | 否 | 需要删除的cookie。cookie的匹配规则和抛出错误的规则参考[setCookies](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#setcookies)。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void> | Promise对象，无返回结果。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误) | Parameter error. |
| [1007900999](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900999-内部错误) | Internal Error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';

4. let cookieRepository = rcp.CookieRepository.create('myRepo');
5. let cookie: rcp.ResponseCookie = {
6. name:'session_1',
7. value:'10001',
8. domain:'www.example.com', // 域名请根据实际业务配置
9. maxAge: 60,
10. isSecure: true
11. }
12. cookieRepository.deleteCookies(cookie).then(() => {
13. console.info('deleteCookies success.');
14. }).catch((err: BusinessError) => {
15. console.error(`deleteCookies error, error code is ${err.code}, error data is ${err.data}`);
16. })
```

### deleteCookiesByUrl

PhonePC/2in1TabletTVWearable

deleteCookiesByUrl(url: URL): Promise<void>

根据url从cookie仓库删除cookie。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URL](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#url) | 是 | HTTP请求的url，用于匹配cookie。匹配规则符合[RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265)协议。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void> | Promise对象，无返回结果。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900999](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900999-内部错误) | Internal Error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';
3. import { url } from '@kit.ArkTS';

5. let cookieRepository = rcp.CookieRepository.create('myRepo');
6. cookieRepository.deleteCookiesByUrl(url.URL.parseURL('https://www.example.com')).then(() => {
7. console.info('deleteCookiesByUrl success.');
8. }).catch((err: BusinessError) => {
9. console.error(`deleteCookiesByUrl error, error code is ${err.code}, error data is ${err.data}`);
10. })
```

### identifier

PhonePC/2in1TabletTVWearable

get identifier(): string

获取cookie仓库标识。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| string | 返回cookies仓库标识。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. let cookieRepository = rcp.CookieRepository.create('myRepo');
4. let identifier = cookieRepository.identifier;
5. console.info(`identifier is: ${identifier}`);
```

## TransferConfiguration

PhonePC/2in1TabletTVWearable

TransferConfiguration接口为开发者提供了一组选项，用于调整会话中HTTP请求期间的数据传输行为。这包括与自动重定向和超时配置相关的设置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| autoRedirect | boolean | 否 | 是 | 指定HTTP客户端是否应自动遵循重定向。如果设置为true，客户端将自动遵循HTTP重定向；否则，不会自动重定向。默认值为true。 |
| maxAutoRedirects | number | 否 | 是 | 请求要遵循的最大重定向次数，如果autoRedirect属性为true，则需要对其设置。  取值范围：1~2147483647。  默认值为50。  **起始版本：** 5.0.0(12) |
| timeout | [Timeout](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeout) | 否 | 是 | 配置HTTP请求的超时值，允许开发者定义连接和传输数据所允许的最长时间。如果未设置，则使用默认时间。 |
| assumesHTTP3Capable | boolean | 否 | 是 | 指定连接是否具有HTTP/3功能，true代表连接具有HTTP/3功能，false代表没有，默认为false。 |
| pathPreference | [PathPreference](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pathpreference) | 否 | 是 | HTTP请求路径首选项，此处配置的为建议路径，在实际使用过程中，系统会决定使用哪个路径。可以是'auto'或'cellular'路径。默认为'auto'路径。 |
| serviceType | [ServiceType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#servicetype) | 否 | 是 | 服务类型。默认为undefined。 |
| pausePolicy | [PausePolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#pausepolicy) | 否 | 是 | 请求暂停策略。  **起始版本：** 5.0.0(12) |
| tcp | [TcpConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tcpconfiguration) | 否 | 是 | TCP连接的相关配置。  **起始版本：** 6.0.0(20) |
| connectionReusePolicy | [ConnectionReusePolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#connectionreusepolicy) | 否 | 是 | HTTP连接复用方式。默认是'naive'。  **起始版本：** 6.1.0(23) |
| throwErrorWhenEnableCellularFailed | boolean | 否 | 是 | 配置当请求的pathPreference为'cellular'且蜂窝网络启用失败时是否抛出错误码。设置为true，表示抛出蜂窝连接超时错误码[1007900986](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900986-建立蜂窝链接超时)；false表示不抛错误码，使用其他可用网络（如Wi-Fi）发送请求。默认值为false。  **起始版本：** 6.1.1(24) |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const transferConfig: rcp.TransferConfiguration = {
4. autoRedirect: true,
5. timeout: {
6. connectMs: 5000,
7. transferMs: 10000
8. },
9. assumesHTTP3Capable: true,
10. pathPreference: "cellular",
11. connectionReusePolicy: "balanced"
12. };

14. // Use the configuration in the session creation
15. const session = rcp.createSession({ requestConfiguration: { transfer: transferConfig } });
```

## TracingConfiguration

PhonePC/2in1TabletTVWearable

TracingConfiguration接口使开发者能够在会话中的HTTP请求期间捕获详细的跟踪信息。跟踪有助于调试、性能分析和深入了解通信过程中的数据流。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| verbose | boolean | 否 | 是 | 启用详细跟踪，捕获有关HTTP请求/响应流的大量信息。默认值为false，true表示开启捕获，false表示不开启。 |
| infoToCollect | [InfoToCollect](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#infotocollect) | 否 | 是 | 配置要收集的特定类型的信息事件。默认无事件需要收集。 |
| collectTimeInfo | boolean | 否 | 是 | 指示在跟踪过程中是否应收集与时间相关的信息，true代表收集，false代表不收集，默认值为false。 |
| httpEventsHandler | [HttpEventsHandler](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpeventshandler) | 否 | 是 | 为HTTP请求/响应过程中的特定操作定义响应处理程序的回调。默认值为undefined。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. // Define a custom response handler
4. const customHttpEventsHandler: rcp.HttpEventsHandler = {
5. onDataReceive: (incomingData: ArrayBuffer) => {
6. // Custom logic for handling incoming data
7. console.info(`Received data length: ${incomingData.byteLength}`);
8. return incomingData.byteLength;
9. },
10. onUploadProgress: (totalSize: number, transferredSize: number) => {
11. // Custom logic for handling upload progress
12. console.info(`Upload progress: ${transferredSize} of ${totalSize}`);
13. },
14. onDownloadProgress: (totalSize: number, transferredSize: number) => {
15. // Custom logic for handling download progress
16. console.info(`Download progress: ${transferredSize} of ${totalSize}`);
17. },
18. onHeaderReceive: (headers: rcp.ResponseHeaders) => {
19. // Custom logic for handling response headers
20. console.info(`Received headers: ${JSON.stringify(headers)}`);
21. },
22. onDataEnd: () => {
23. // Custom logic for handling data transfer completion
24. console.info("Data transfer complete");
25. },
26. onCanceled: () => {
27. // Custom logic for handling cancellation
28. console.info("Request/response canceled");
29. },
30. onStatusCodeReceive: (statusCode: number, request?: rcp.Request) => {
31. // Custom logic for handling statusCode
32. console.info(`Received statusCode: ${statusCode}`);
33. }
34. };

36. // Configure tracing settings
37. const tracingConfig: rcp.TracingConfiguration = {
38. verbose: true,
39. infoToCollect: {
40. textual: true,
41. incomingHeader: true,
42. outgoingHeader: true,
43. incomingData: true,
44. outgoingData: true,
45. incomingSslData: true,
46. outgoingSslData: true
47. },
48. collectTimeInfo: true,
49. httpEventsHandler: customHttpEventsHandler
50. };

52. // Use the configuration in the session creation
53. const session = rcp.createSession({requestConfiguration: {tracing: tracingConfig}});
54. console.info(`session id: ${session.id}`);
```

## ProxyConfiguration

PhonePC/2in1TabletTVWearable

type ProxyConfiguration = 'system' | 'no-proxy' | [WebProxy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#webproxy)

ProxyConfiguration接口允许开发者为会话中的HTTP请求配置代理设置，从而提供在系统、自定义或无代理之间进行选择的灵活性。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| 'system' | HTTP代理配置。'system'：表示使用系统代理配置。 |
| 'no-proxy' | HTTP代理配置。'no-proxy'：表示不使用代理。 |
| [WebProxy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#webproxy) | HTTP代理配置。WebProxy：表示提供自定义代理设置。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. // Configure system proxy (default)
4. const systemProxyConfig = "system";

6. // Configure custom proxy
7. const customProxyConfig: rcp.WebProxy = {
8. url: "http://custom-proxy.example.com",
9. createTunnel: "always",
10. exclusions: ["http://exclude.example.com"],
11. security: {
12. certificate: {
13. content: "-----BEGIN CERTIFICATE-----\n...",
14. type: "PEM",
15. key: "-----BEGIN PRIVATE KEY-----\n...", // 请根据实际业务选择合适的key
16. keyPassword: "your-password"
17. },
18. serverAuthentication: {
19. credential: {
20. username: "proxy-username",
21. password: "proxy-password"
22. },
23. authenticationType: "basic"
24. }
25. }
26. };

28. // Configure no proxy
29. const noProxyConfig = "no-proxy";

31. // Use the proxy configuration in the session creation
32. const sessionWithSystemProxy = rcp.createSession({ requestConfiguration: { proxy: systemProxyConfig } });
33. console.info(`sessionWithSystemProxy id: ${sessionWithSystemProxy.id}`);

35. const sessionWithCustomProxy = rcp.createSession({ requestConfiguration: { proxy: customProxyConfig } });
36. console.info(`sessionWithCustomProxy id: ${sessionWithCustomProxy.id}`);

38. const sessionWithNoProxy = rcp.createSession({ requestConfiguration: { proxy: noProxyConfig } });
39. console.info(`sessionWithNoProxy id: ${sessionWithNoProxy.id}`);
```

## DnsConfiguration

PhonePC/2in1TabletTVWearable

允许开发者为会话中的HTTP请求配置域名系统（DNS）设置。它提供了指定DNS规则的灵活性，包括自定义DNS服务器或静态DNS规则。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| dnsRules | [DnsServers](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#dnsservers) | [StaticDnsRules](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#staticdnsrules) | [DynamicDnsRule](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#dynamicdnsrule) | 否 | 是 | 配置DNS规则，默认值为undefined。  DnsServers：表示优先使用指定的DNS服务器解析主机名。  StaticDnsRules：静态DNS规则，表示如果hostname匹配，则优先使用指定的地址。  DynamicDnsRule：动态DNS规则，表示优先使用函数中返回的地址。  **说明：** 针对同一域名配置多个静态或者动态DNS规则后，默认情况下，仅有最后一个IP地址生效。如果希望多个IP地址同时生效，在6.0.0(20)版本后，支持同一域名配置多个静态或者动态DNS规则，此时将happyEyeballOnDnsRule设置为true可以让多个IP地址同时生效。 |
| dnsOverHttps | [DnsOverHttpsConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#dnsoverhttpsconfiguration) | 否 | 是 | DNS over HTTPS配置。默认值为undefined。  如果设置，则优先使用DNS服务器解析的地址。 |
| happyEyeballOnDnsRule | boolean | 否 | 是 | 是否启用Happy Eyeball竞速连接。  当特定地址或地址族（IPv4或IPv6）被阻止、损坏或网络不佳质量差时，可通过Happy Eyeball竞速连接更快地建立连接。  true：当DNS规则（dnsRules参数）被设置时启用Happy Eyeball竞速连接功能。  false：当DNS规则（dnsRules参数）被设置时不启用Happy Eyeball竞速连接功能。  默认值是false。  **起始版本：** 6.0.0(20)  **说明：** 只有设置了DNS规则（dnsRules参数）时该配置项才有意义；否则，Happy Eyeball竞速连接功能是默认启用的，而且无法关闭，此时设置此选项无任何作用。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. // Configure custom DNS servers
4. const customDnsServers: rcp.DnsServers = [
5. { ip: "8.8.8.8" },
6. { ip: "8.8.4.4", port: 53 }
7. ];

9. // Configure static DNS rules
10. const staticDnsRules: rcp.StaticDnsRules = [
11. { host: "example.com", port: 80, ipAddresses: ["192.168.1.1", "192.168.1.2"] },
12. { host: "sub.example.com", port: 443, ipAddresses: ["192.168.2.1"] }
13. ];

15. // Configure DNS over HTTPS
16. const dohConfig: rcp.DnsOverHttpsConfiguration = {
17. url: "https://dns.example.com/dns-query",
18. skipCertificatesValidation: true
19. };

21. // Use DNS configuration in the session creation.
22. const sessionWithCustomDns = rcp.createSession({ requestConfiguration: { dns: { dnsRules: customDnsServers } } });
23. const sessionWithStaticDns = rcp.createSession({
24. requestConfiguration: {
25. dns: {
26. // for example.com, '192.168.1.2' is effective.
27. // for sub.example.com, '192.168.2.1' is effective.
28. dnsRules: staticDnsRules,
29. }
30. }
31. });
32. const sessionWithDoh = rcp.createSession({ requestConfiguration: { dns: { dnsOverHttps: dohConfig } } });

34. // Enable happy eyeball in the session creation when dns rules is set.
35. const sessionWithStaticDnsRulesAndHappyEyeball = rcp.createSession({
36. requestConfiguration: {
37. dns: {
38. dnsRules: staticDnsRules, // Set dns rules here.
39. happyEyeballOnDnsRule: true, // Enable happy eyeball here.
40. }
41. }
42. });

44. // Enable happy eyeball in the request configuration when dns rules is set.
45. const request = new rcp.Request('https://example.com');
46. request.configuration = {
47. dns: {
48. dnsRules: staticDnsRules, // Set dns rule here.
49. happyEyeballOnDnsRule: true, // Enable happy eyeball here.
50. }
51. };
```

## DnsOverHttpsConfiguration

PhonePC/2in1TabletTVWearable

允许开发者配置HTTPS上的DNS（DOH）设置，从而通过HTTPS端点实现安全的DNS解析。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 否 | 否 | DOH端点的URL或字符串表示形式。 |
| skipCertificatesValidation | boolean | 否 | 是 | 指定是否跳过DOH终结点的SSL/TLS证书验证。true代表跳过，false代表不跳过，默认值为false。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. // Configure DNS over HTTPS settings
4. const dohConfig: rcp.DnsOverHttpsConfiguration = {
5. url: "https://dns.example.com/dns-query",
6. skipCertificatesValidation: true
7. };

9. // Use the DNS over HTTPS configuration in the session creation
10. const sessionWithDoh = rcp.createSession({ requestConfiguration: { dns: { dnsOverHttps: dohConfig } } });
```

## SecurityConfiguration

PhonePC/2in1TabletTVWearable

SecurityConfiguration接口允许开发者在会话中配置与安全相关的设置，包括证书和服务器身份验证。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| remoteValidation | 'system' | 'skip' | [CertificateAuthority](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#certificateauthority) | [ValidationCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#validationcallback) | 否 | 是 | 证书颁发机构（CA），用于验证远程服务器的身份。默认值为'system'。  如果未设置此字段，系统CA将被用于验证远程服务器的标识。  'system'：表示使用系统CA配置。  'skip'：跳过验证。  CertificateAuthority：证书颁发机构（CA）验证。  ValidationCallback：自定义证书校验。  **说明：** 从5.0.0(12)版本开始，新增支持ValidationCallback类型。 |
| certificate | [ClientCertificate](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#clientcertificate) | 否 | 是 | 发送到远程服务器的客户端证书，用于远程服务器使用其验证委托人的身份证明。默认值为undefined，表示服务器不需要验证客户端。 |
| tlsOptions | 'system' | [CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ciphersuite)[] | [TlsV13Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv13option) | [TlsV12Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv12option)| [TlsV11Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv11option) | [TlsV10Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv10option) | 否 | 是 | TLS版本选择器，用于选择TLS的版本，默认为'system'。  'system'：表示使用系统的TLS版本。  [CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ciphersuite)[]：用来声明加密套件的类型的数组。  [TlsV13Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv13option)：表示使用TLS1.3版本。  [TlsV12Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv12option)：表示使用TLS1.2版本。  [TlsV11Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv11option)：表示使用TLS1.1版本。  [TlsV10Option](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv10option)：表示使用TLS1.0版本。  **起始版本：** 5.0.0(12) |
| tlsRange | [TlsVersionRangeOptions](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsversionrangeoptions) | 否 | 是 | TLS版本范围配置器，用于设置客户端可使用TLS版本的范围，默认不配置。  **起始版本：** 6.0.0(20) |
| serverAuthentication | [ServerAuthentication](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#serverauthentication) | 否 | 是 | 安全连接期间的服务器身份验证配置。默认不认证。 |
| certificatePinning | [CertificatePinning](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#certificatepinning)| [CertificatePinning](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#certificatepinning)[] | 否 | 是 | 证书锁定配置。  **起始版本：** 5.0.0(12) |
| challenge | [OnAuthenticationChallenge](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#onauthenticationchallenge) | 否 | 是 | 自定义认证挑战。  **起始版本：** 6.1.0(23) |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. // Configure security settings
4. const securityConfig: rcp.SecurityConfiguration = {
5. remoteValidation: "system",
6. certificate: {
7. content: "-----BEGIN CERTIFICATE-----\n...",
8. type: "PEM",
9. key: "-----BEGIN PRIVATE KEY-----\n...", // 请根据自身业务选择合适的key
10. keyPassword: "your-password"
11. },
12. serverAuthentication: {
13. credential: {
14. username: "exampleUser",
15. password: "examplePassword"
16. },
17. authenticationType: "basic"
18. }
19. };

21. // Use the security configuration in the session creation
22. const sessionWithSecurityConfig = rcp.createSession({ requestConfiguration: { security: securityConfig } });
```

## CertificateAuthority

PhonePC/2in1TabletTVWearable

证书颁发机构（CA）用于验证远程服务器的身份。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| content | string | ArrayBuffer | 否 | 是 | 用于验证对等方的证书颁发机构证书捆绑包。是PEM格式。 |
| filePath | string | 否 | 是 | 用于验证对等方的证书颁发机构证书文件的路径。该文件应为PEM格式。 |
| folderPath | string | 否 | 是 | 用于验证对等方包含多个CA证书目录的路径。此目录中的文件应为PEM格式。 |

## ClientCertificate

PhonePC/2in1TabletTVWearable

ClientCertificate接口允许开发者为会话中的安全连接配置与证书相关的设置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| content | string | ArrayBuffer | 否 | 是 | 证书颁发机构（CA）证书的内容。它可以作为字符串或ArrayBuffer提供。 |
| filePath | string | 否 | 是 | 包含证书颁发机构（CA）证书的文件的路径。默认值为undefined。 |
| type | 'PEM' | 'DER' | 'P12' | 否 | 是 | 客户端证书编码格式类型。默认值为undefined。 |
| key | string | 否 | 是 | 客户端证书私钥文件的路径。默认值为undefined。 |
| keyPassword | string | 否 | 是 | 客户端证书密码。默认值为undefined。 |

## ServerAuthentication

PhonePC/2in1TabletTVWearable

HTTP服务器身份验证。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| credential | [Credential](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#credential) | 否 | 否 | 服务器的凭证。默认值为undefined。 |
| authenticationType | [AuthenticationType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#authenticationtype) | 否 | 是 | 服务器的认证类型。如果没有设置，需与服务器协商。 |

## TlsVersionRangeOptions

PhonePC/2in1TabletTVWearable

TLS版本可用范围配置属性，开发者能够设置安全相关TLS版本的上限和下限，并指定该范围内加密套件列表。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| min | [TlsVersion](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsversion) | 否 | 是 | TLS可用最小版本，默认不设置，由系统选择。 |
| max | [TlsVersion](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsversion) | 否 | 是 | TLS可用最大版本，默认不设置，由系统选择。 |
| cipherSuite | [CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ciphersuite)[] | 否 | 是 | TLS可用版本范围内的加密套件列表，默认不设置，由系统选择。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/errorcode-universal#section401-参数检查失败) | 当开发者设置TLS最小版本大于最大版本时，系统将抛出该参数错误码。表示Parameter error. |

## OnAuthenticationChallenge

PhonePC/2in1TabletTVWearable

type OnAuthenticationChallenge = (info: AuthenticationChallengeInfo[], response: Response, challengeCount: number) => ServerAuthentication | null

认证挑战回调函数。开发者可通过此回调函数处理认证挑战。当HTTP响应的状态码为401时，系统会调用此回调函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| info | [AuthenticationChallengeInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#authenticationchallengeinfo)[] | 是 | 认证挑战参数。系统解析响应头中的WWW-Authenticate信息，并将信息转化为键值对。 |
| response | [Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response) | 是 | 此次认证挑战的HTTP响应。 |
| challengeCount | number | 是 | 认证挑战的次数。如果挑战不被服务器认证通过，可能会再次触发认证挑战。系统不限制挑战的次数。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [ServerAuthentication](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#serverauthentication) | null | 返回类型为HTTP服务器的身份验证信息或null。若返回验证信息，系统将使用用户提供的信息进行认证挑战；若返回null，则放弃认证挑战。 |

## AuthenticationChallengeInfo

PhonePC/2in1TabletTVWearable

type AuthenticationChallengeInfo = Record<string, string>

服务器返回的认证挑战信息。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

展开

| 类型 | 说明 |
| --- | --- |
| Record<string, string> | 从WWW-Authenticate中解析到的认证挑战信息，常见的键包括'type'、'realm'等。 |

## Request

PhonePC/2in1TabletTVWearable

HTTP请求。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| id | string | 是 | 否 | 请求对象的唯一标识符。由系统生成。 |
| url | [URL](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#url) | 否 | 否 | HTTP请求的URL。 |
| method | [HttpMethod](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpmethod) | 否 | 否 | 要使用的HTTP方法。默认值为'GET'。 |
| headers | [RequestHeaders](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestheaders) | 否 | 是 | HTTP请求头。默认值为undefined。 |
| content | [RequestContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontent) | 否 | 是 | HTTP请求内容。默认值为undefined。 |
| cookies | [RequestCookies](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcookies) | 否 | 是 | HTTP请求的Cookie。将设置转换为HTTP Cookies标头。默认值为undefined。 |
| transferRange | [TransferRange](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#transferrange) | [TransferRange](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#transferrange)[] | 否 | 是 | HTTP传输范围。转换为HTTP Range头。带有range头的HTTP请求要求服务器只返回HTTP响应的一部分。默认值为undefined。 |
| configuration | [Configuration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#configuration) | 否 | 是 | HTTP请求配置。用于覆盖默认或会话范围的设置。默认值为undefined。 |
| destination | [ResponseBodyDestination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsebodydestination) | 否 | 是 | HTTP响应体放置位置。  **起始版本：** 5.0.0(12) |
| cacheControl | [CacheControl](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cachecontrol) | 否 | 是 | HTTP请求缓存控制配置。若配置，则[SessionConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#sessionconfiguration)中的配置的缓存控制不生效。默认值为undefined。  **起始版本：** 6.0.0(20) |
| connectOnly | boolean | 否 | 是 | 此选项用于确定请求是否仅用于建立连接。如果设置为true，则表示本次请求仅用于建立连接；如果设置为false，则表示本次请求可以传输数据。默认值为false。  **起始版本：** 6.1.1(24) |

### constructor

PhonePC/2in1TabletTVWearable

constructor(url: URLOrString, method?: HttpMethod, headers?: RequestHeaders, content?: RequestContent, cookies?: RequestCookies, transferRange?: TransferRange | TransferRange[], configuration?: Configuration)

提供用于创建Request对象的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | 请求的地址类型，在构造函数中，参数可以是 URLOrString，但 URL 只是 URL，字符串需要转换为URL。 |
| method | [HttpMethod](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpmethod) | 否 | HTTP 请求方法。默认是GET。 |
| headers | [RequestHeaders](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestheaders) | 否 | HTTP请求头。默认值为undefined。 |
| content | [RequestContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontent) | 否 | HTTP 请求正文。默认值为undefined。 |
| cookies | [RequestCookies](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcookies) | 否 | HTTP 请求 cookie。该设置将转换为 HTTP Cookies header。 |
| transferRange | [TransferRange](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#transferrange)| [TransferRange](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#transferrange)[] | 否 | HTTP 传输范围。该设置将转换为 HTTP Range header。 |
| configuration | [Configuration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#configuration) | 否 | HTTP 请求配置。见[Configuration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#configuration)。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. let headers: rcp.RequestHeaders = {
4. "accept": "application/json"
5. };
6. let content = "data to send";
7. let configuration: rcp.Configuration = {
8. transfer: {
9. timeout: { connectMs: 60000, transferMs: 60000 }
10. }
11. };
12. let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
13. let transferRange: rcp.TransferRange = { from: 100, to: 200 };
14. let req = new rcp.Request("http://example.com", "POST", headers, content, cookies, transferRange, configuration);
```

## URL

PhonePC/2in1TabletTVWearable

type URL = url.URL

请求的地址类型，链接到@[ohos.url](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-url)中的URL。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| url.URL | 表示值的类型为@ohos.url.URL，请求的地址类型，可取任意值。 |

## X509Cert

PhonePC/2in1TabletTVWearable

type X509Cert = cert.X509Cert

提供 x509 证书类型，链接到@[ohos.security.cert](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-cert)中的X509Cert。

取值范围请见下表。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| cert.X509Cert | 表示值的类型为@ohos.security.cert.X509Cert，可取任意值。 |

## File

PhonePC/2in1TabletTVWearable

type File = fs.File

文件系统中的文件，链接到@[ohos.file.fs](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fs)中的File。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| fs.File | 表示值的类型为@ohos.file.fs.File，可取任意值。 |

## RandomAccessFile

PhonePC/2in1TabletTVWearable

type RandomAccessFile = fs.RandomAccessFile

可以随机访问的文件，链接到@[ohos.file.fs](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fs)中的RandomAccessFile。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| fs.RandomAccessFile | 表示值的类型为@ohos.file.fs.RandomAccessFile，可取任意值。 |

## Stream

PhonePC/2in1TabletTVWearable

type Stream = fs.Stream

提供数据流的形式，链接到@[ohos.file.fs](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-file-fs)中的Stream。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| fs.Stream | 表示值的类型为@ohos.file.fs.Stream，可取任意值。 |

## RawDataContent

PhonePC/2in1TabletTVWearable

type RawDataContent = string | ArrayBuffer | object

ArkTs的基本类型数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| string | 表示数据以文本字符串的形式存在，可取任意值。 |
| ArrayBuffer | 表示数据以二进制形式存在，可取任意值。 |
| object | 表示数据以对象的形式存在，可取任意值。 |

## FileDescriptor

PhonePC/2in1TabletTVWearable

type FileDescriptor = number

文件的描述符，用于访问文件或者I/O设备的抽象表示。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| number | 表示值的类型为number，可取任意值。 |

## LocalFile

PhonePC/2in1TabletTVWearable

type LocalFile = [FileDescriptor](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#filedescriptor) | [File](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#file) | [RandomAccessFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#randomaccessfile)

具有文件特性的对象，允许用户使用不同类型的文件描述符或文件对象进行操作。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| [FileDescriptor](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#filedescriptor) | 表示文件的描述符。文件描述符是一个整数，用于标识一个打开的文件。 |
| [File](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#file) | 文件系统中的文件，用于获取文件的描述符、路径和名称，以及对文件的锁定和解锁操作。 |
| [RandomAccessFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#randomaccessfile) | 提供随机访问文件的操作功能。用于处理随机访问文件的一种类型。提供了文件描述符、文件指针的读取，以及文件指针的设置和文件的写入操作。 |

## WriteFile

PhonePC/2in1TabletTVWearable

提供向文件写入数据的函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### write

PhonePC/2in1TabletTVWearable

write(buffer: ArrayBuffer): Promise<void | number>

向文件写入数据，使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | ArrayBuffer | 是 | 向文件中写入的数据。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void | number> | Promise对象。无返回结果，或者返回写入的number类型数据。 |

## ReadFile

PhonePC/2in1TabletTVWearable

提供从文件中读取数据的函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### read

PhonePC/2in1TabletTVWearable

read(buffer: ArrayBuffer): Promise<number>

从文件中读取数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | ArrayBuffer | 是 | 需要读取数据的文件。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<number> | Promise对象，返回从文件中读取到的数据，类型为number。 |

## WriteStream

PhonePC/2in1TabletTVWearable

提供将数据写入流中的函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### write

PhonePC/2in1TabletTVWearable

write(buffer: ArrayBuffer): Promise<void | number>

从文件中写入数据。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | ArrayBuffer | 是 | 需要写入流中的数据。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void | number> | Promise对象。无返回结果，或者返回写入的number类型数据。 |

## SyncWriteStream

PhonePC/2in1TabletTVWearable

提供同步将数据写入流中的函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### writeSync

PhonePC/2in1TabletTVWearable

writeSync(buffer: ArrayBuffer): void | number

将数据写入流中。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | ArrayBuffer | 是 | 需要写入流中的数据。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| void | 无返回值。 |
| number | 返回写入的number类型数据。 |

## ReadStream

PhonePC/2in1TabletTVWearable

提供从流中读取数据的函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### read

PhonePC/2in1TabletTVWearable

read(buffer: ArrayBuffer): Promise<number>

从流中读取数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | ArrayBuffer | 是 | 需要写入流中的数据。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<number> | Promise对象，返回从文件中读取到的数据，类型为number。 |

## SyncReadStream

PhonePC/2in1TabletTVWearable

提供同步从流中读取数据的函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### readSync

PhonePC/2in1TabletTVWearable

readSync(buffer: ArrayBuffer): number

从流中读取数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | ArrayBuffer | 是 | 需要写入流中的数据。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| number | 返回写入的number类型数据。 |

## DownloadedTo

PhonePC/2in1TabletTVWearable

用户在发起请求时通过[DownloadToFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtofile)指定的路径。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| path | [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path) | 否 | 否 | 如果请求目标（[Request.destination](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request)）是下载到文件时，path表示文件保存的路径。 |
| requestSkipped | true | 否 | 是 | 当前仅支持true，若配置时选择此项则默认跳过请求，若不想跳过则不必选择此项。 |

## TargetFile

PhonePC/2in1TabletTVWearable

下载后的数据存放在本地设备的指定目录中，通常是下载文件夹或指定的默认存储位置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| path | [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path) | 否 | 否 | 指定的数据下载路径。 |
| skipRequest | boolean | 否 | 是 | 是否跳过请求，true代表跳过，false代表不跳过，默认值为false。 |

## TargetFileCallback

PhonePC/2in1TabletTVWearable

type TargetFileCallback = (request: [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request), suggestedPath: [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path)) => [TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile) | Promise<[TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile)>

[TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile)回调函数，返回一个[TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile)对象，可以使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 是 | 表示入参的类型为一个HTTP请求。 |
| suggestedPath | [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path) | 是 | 表示入参的类型为[Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path)，请求中指定的路径。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile) | 回调函数，返回[TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile)对象。 |
| Promise<[TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile)> | Promise对象，返回[TargetFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfile)对象，表示下载数据的存放位置。 |

## IncomingDataCallback

PhonePC/2in1TabletTVWearable

type IncomingDataCallback = (incomingData: ArrayBuffer) => void | Promise<void>

处理下载数据的回调函数。可以使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| incomingData | ArrayBuffer | 是 | 表示需要处理的ArrayBuffer类型数据。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| void | 回调函数，无返回值。 |
| Promise<void> | Promise对象，无返回结果。 |

## UploadFromFile

PhonePC/2in1TabletTVWearable

UploadFromFile表示一种文件上传的方式，允许客户端将本地计算机上的文件上传到服务器。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| fileOrPath | [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path) | [LocalFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#localfile) | [ReadFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#readfile) | 是 | 否 | 表示需要上传的文件或者上传文件的路径，参考[应用文件](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-file)。 |

### constructor

PhonePC/2in1TabletTVWearable

constructor(fileOrPath: Path | LocalFile | ReadFile)

提供用于创建UploadFromFile对象的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| fileOrPath | [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path) | [LocalFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#localfile) | [ReadFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#readfile) | 是 | 表示需要上传的文件或者上传文件的路径，参考[应用文件](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-file)。 |

## UploadFromStream

PhonePC/2in1TabletTVWearable

UploadFromStream表示以流的形式进行上传操作。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| stream | [Stream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#stream) | [ReadStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#readstream) | [SyncReadStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#syncreadstream) | 是 | 否 | 表示需要上传的流。 |

### constructor

PhonePC/2in1TabletTVWearable

constructor(stream: Stream | ReadStream | SyncReadStream)

提供用于创建UploadFromStream对象的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| stream | [Stream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#stream) | [ReadStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#readstream) | [SyncReadStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#syncreadstream) | 是 | 表示需要上传的流。 |

## DownloadToFile

PhonePC/2in1TabletTVWearable

type DownloadToFile = { kind: 'file'; file: TargetFileCallback; } | { kind: 'file'; file: Path; keepLocal?: boolean; } | { kind: 'file'; file: LocalFile | WriteFile; } | { kind: 'folder'; path: Path; keepLocal?: boolean; }

将文件下载到文件夹或文件中。如果下载到文件夹，文件名将与服务器中的文件名相同。取值范围为以下表中类型的并集。其中，kind 用于指定想要下载到文件或目录，file 指的是具体要下载到的目标文件或目录（参考[应用文件](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-file)）。

取值范围为以下表中类型的并集。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| { kind: 'file'; file: [TargetFileCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfilecallback); } | 表示键kind的键值为'file'，键file的键值为[TargetFileCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#targetfilecallback)。 |
| { kind: 'file'; file: [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path); keepLocal?: boolean; } | 表示键kind的值为'file'，键file的值为[Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path)对象，其中keepLocal为可选参数值，当本地文件名和下载的文件名相同时，不会重复下载。 |
| { kind: 'file'; file: [LocalFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#localfile)| [WriteFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#writefile); } | 表示键kind的值为'file'，键file的值为[LocalFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#localfile)或[WriteFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#writefile)对象。 |
| { kind: 'folder'; path: [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path); keepLocal?: boolean; } | 键kind的值为'folder'，键path的值为[Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path)对象，其中keepLocal为可选参数值，当本地文件夹名和下载的文件夹名相同时，不会重复下载。 |

## DownloadToStream

PhonePC/2in1TabletTVWearable

type DownloadToStream = { kind: 'stream'; stream: Stream | WriteStream | SyncWriteStream; }

将文件下载到一个数据流中。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| { kind: 'stream'; stream: [Stream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#stream)| [WriteStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#writestream)| [SyncWriteStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#syncwritestream) } | 表示键kind值为'stream'，键stream的值为  [Stream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#stream)或[WriteStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#writestream)或[SyncWriteStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#syncwritestream)的对象。 |

## PausePolicy

PhonePC/2in1TabletTVWearable

请求的暂停策略。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| receiving | [ReceivingPausePolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#receivingpausepolicy) | 否 | 是 | 设置暂停响应体接收的策略。 |
| sending | [SendingPausePolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#sendingpausepolicy) | 否 | 是 | 设置暂停请求体发送的策略。 |

## ReceivingPauseByTimeout

PhonePC/2in1TabletTVWearable

暂停接收流程的按超时的策略。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'timeout' | 否 | 否 | 策略类型。用来表示这是按超时暂停接收流程的策略。 |
| timeoutMs | number | 否 | 否 | 超时时间，如果超过了该时间，框架还没从服务端收到数据，就会暂停请求。单位为毫秒。  取值范围：1~1000。  默认值为 0。 |

## ReceivingPauseByCache

PhonePC/2in1TabletTVWearable

暂停接收流程的按缓存的策略。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'cacheSize' | 否 | 否 | 策略类型。用来表示这是按缓存暂停接收流程的策略。 |
| size | number | 否 | 否 | 缓存策略的最大值，框架缓存的数据超过该值，应用一直不处理，就会暂停请求。取值范围[0, 1048576]。 |

## ReceivingPausePolicy

PhonePC/2in1TabletTVWearable

type ReceivingPausePolicy = ReceivingPauseByCache | ReceivingPauseByTimeout

接收流程的暂停策略。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| [ReceivingPauseByCache](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#receivingpausebycache) | 策略的缓存大小。 |
| [ReceivingPauseByTimeout](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#receivingpausebytimeout) | 策略的超时时间。 |

## NetworkOutputQueue

PhonePC/2in1TabletTVWearable

const NetworkOutputQueue: NetworkOutputQueueConstructor

通过 new NetworkInputQueue()来创建一个[INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

## NetworkOutputQueueConstructor

PhonePC/2in1TabletTVWearable

NetworkOutputQueueConstructor是一个[INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue)的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### new

PhonePC/2in1TabletTVWearable

new (): INetworkOutputQueue

创建一个[INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue) | 返回一个同步读队列对象。 |

### new

PhonePC/2in1TabletTVWearable

new (maxSize: number): INetworkOutputQueue

创建一个[INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| maxSize | number | 是 | 队列大小，表示框架可写入的最大字节数。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue) | 返回一个同步读队列对象。 |

### new

PhonePC/2in1TabletTVWearable

new (maxSize: number, pausePolicyOverride: ReceivingPausePolicy): INetworkOutputQueue

创建一个[INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| maxSize | number | 是 | 队列大小，表示可写入的最大字节数。 |
| pausePolicyOverride | [ReceivingPausePolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#receivingpausepolicy) | 是 | 请求的接收暂停策略。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue) | 返回一个同步读队列对象。 |

## INetworkOutputQueue

PhonePC/2in1TabletTVWearable

INetworkOutputQueue是用读响应体的同步读队列。通过new [NetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#networkoutputqueue)()来构造。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### read

PhonePC/2in1TabletTVWearable

read(maxBytesToRead: number): ArrayBuffer

从队列中读取一段数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| maxBytesToRead | number | 是 | 读取到的数据的最大字节数。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| ArrayBuffer | 读取到的二进制数据。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900990](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900990-内存不足) | Out of memory. |

### readInto

PhonePC/2in1TabletTVWearable

readInto(buffer: ArrayBuffer): number

将数据从队列中读取并存入指定的缓冲区。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | ArrayBuffer | 是 | 读到参数中的buffer里面。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| number | 读取的二进制数据的字节数。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900990](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900990-内存不足) | Out of memory. |

### getStoredBytes

PhonePC/2in1TabletTVWearable

getStoredBytes(): number

获取队列中的数据的大小。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| number | 获取队列中的数据的大小。 |

## ResponseBodyDestination

PhonePC/2in1TabletTVWearable

type ResponseBodyDestination = 'array-buffer'| IncomingDataCallback | DownloadToFile | DownloadToStream | INetworkOutputQueue

ResponseBodyDestination类型指定了响应的目标位置或目的地，指示HTTP客户端应该将响应数据发送到哪个位置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| 'array-buffer' | 表示值的类型为'array-buffer'类型数据。默认将响应体写到内存。 |
| [IncomingDataCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#incomingdatacallback) | 表示值的类型为[IncomingDataCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#incomingdatacallback)类型数据。将响应体写到回调函数中。 |
| [DownloadToFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtofile) | 表示值的类型为[DownloadToFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtofile)类型数据。将响应体写到文件中。 |
| [DownloadToStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtostream) | 表示值的类型为[DownloadToStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadtostream)类型对象。将响应体写到自定义的流中。 |
| [INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue) | 表示值的类型为[INetworkOutputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkoutputqueue)类型对象。把响应体写到队列。 |

## URLOrString

PhonePC/2in1TabletTVWearable

type URLOrString = [URL](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#url) | string

URLOrString类型是表示URL对象或表示URL的字符串的并集类型。可以作为HTTP/HTTPS地址的入参。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| [URL](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#url) | URL对象，可以作为HTTP/HTTPS地址的入参 |
| string | URL的字符串，可以作为HTTP/HTTPS地址的入参 |

## PathPreference

PhonePC/2in1TabletTVWearable

type PathPreference = 'auto' | 'cellular'

HTTP请求路径偏好设置。此设置仅为开发者的建议，实际使用路径由系统决定。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| 'auto' | 表示系统自动选择路径。 |
| 'cellular' | 表示蜂窝网络路径。 |

## ConnectionReusePolicy

PhonePC/2in1TabletTVWearable

type ConnectionReusePolicy = 'balanced' | 'forbidden' | 'naive'

HTTP连接复用方式。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

展开

| 类型 | 说明 |
| --- | --- |
| 'balanced' | 表示均衡地使用HTTP连接。系统会选择当前负载最低的HTTP连接。 |
| 'forbidden' | 表示禁止连接复用。每次请求都会创建新的HTTP连接。 |
| 'naive' | 表示使用简易的连接复用方式。系统会选择找到的第一个可用的HTTP连接。 |

## IpAddress

PhonePC/2in1TabletTVWearable

type IpAddress = string

IP地址类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| string | 表示IP地址只是一个字符串。它可以是IPv4字符串或IPv6字符串。 |

## DnsServers

PhonePC/2in1TabletTVWearable

type DnsServers = IpAndPort[]

DnsServers接口允许开发者在DnsConfiguration中配置DNS设置时，指定自定义DNS服务器。它提供了一种灵活的方式来定义IP地址和相关端口的列表。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| [IpAndPort](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ipandport)[] | 表示值的类型为[IpAndPort](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ipandport)数组，数组成员为地址和端口键值对。 |

## IpAndPort

PhonePC/2in1TabletTVWearable

IpAndPort接口允许开发者定义IP地址和可选端口号。它通常用于需要同时指定IP地址和端口的情况，例如在DnsServers接口中配置自定义DNS服务器时。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| ip | [IpAddress](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ipaddress) | 否 | 否 | 要关联的IP地址。IPv4或IPv6地址。 |
| port | number | 否 | 是 | 可选端口号。取值范围[0, 65535]，默认值为53。 |

## ServiceType

PhonePC/2in1TabletTVWearable

type ServiceType = 'default' | 'background' | 'realtimeVoice' | 'realtimeVideo' | 'callSignaling' | 'realtimeGame' | 'normalGame' | 'shortVideo' | 'longVideo' | 'livestreamingAnchor' | 'livestreamingWatcher' | 'download' | 'upload' | 'browser'

网络服务类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| 'default' | 表示默认服务类型，适用于大多数一般性的服务需求。  **说明：** 除'default'外，其他类型均为5.0.0(12)新增类型。 |
| 'background' | 表示后台服务类型，适用于在后台运行的任务，如定时任务、后台数据同步或推送通知等。 |
| 'realtimeVoice' | 表示实时语音服务类型，适用于实时语音通信，如电话、视频会议或即时通话等。 |
| 'realtimeVideo' | 表示实时视频服务类型，适用于实时视频通信。 |
| 'callSignaling' | 表示呼叫信号服务类型，适用于电话呼叫信号的传输和管理，包括呼叫建立、挂断、转接等操作。 |
| 'realtimeGame' | 表示实时游戏服务类型，适用于实时多人游戏，需要低延迟和高可靠性，以确保玩家之间的同步和游戏体验。 |
| 'normalGame' | 表示普通游戏服务类型，适用于非实时的游戏服务，比如单人游戏、离线游戏或非竞技类游戏。 |
| 'shortVideo' | 表示短视频服务类型，适用于短视频的上传、下载和播放。 |
| 'longVideo' | 表示长视频服务类型，适用于长视频的服务。 |
| 'livestreamingAnchor' | 表示直播播控服务类型，适用于直播平台上的主播端。 |
| 'livestreamingWatcher' | 表示直播观看服务类型，适用于直播平台上的观众端。 |
| 'download' | 表示下载服务类型，适用于资源下载服务。 |
| 'upload' | 表示上传服务类型，适用于上传资源服务。 |
| 'browser' | 表示浏览器服务类型，适 用于浏览器中的网页加载和交互。 |

## HttpMethod

PhonePC/2in1TabletTVWearable

type HttpMethod = 'GET' | 'POST' | 'HEAD' | 'PUT' | 'DELETE' | 'PATCH' | 'OPTIONS' | (string & NonNullable<unknown>)

HttpMethod是HTTP库中的一种类型，代表网络请求中使用的各种HTTP方法。HTTP方法定义了要对给定资源执行的操作。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| 'GET' | 表示网络请求的方式为GET，通常用于从服务器获取数据，如获取网页、图片、API 数据等。 |
| 'POST' | 表示网络请求的方式为POST，通常用于向服务器发送数据，如提交表单、上传文件等。 |
| 'HEAD' | 表示网络请求的方式为HEAD，类似于 GET 请求，但只请求资源的头部信息，不返回资源本身。通常用于检查资源是否存在、获取资源的元数据等。 |
| 'PUT' | 表示网络请求的方式为PUT，通常用于更新服务器上的现有资源。 |
| 'DELETE' | 表示网络请求的方式为DELETE，通常用于删除服务器上的资源。 |
| 'PATCH' | 表示网络请求的方式为PATCH，通常用于对现有资源进行部分更新。 |
| 'OPTIONS' | 表示网络请求的方式为OPTIONS，可查询目标资源的通信选项。通常用于跨域请求，询问服务器支持哪些 HTTP 方法。 |
| (string & NonNullable<unknown>) | 用以确保 HttpMethod 类型的值必须是非空字符串。 |

## RequestHeaders

PhonePC/2in1TabletTVWearable

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; }

定义请求头类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| { [k: string]: string | string[] | undefined;  'authorization'?: string;  'accept'?: [ContentType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contenttype) | [ContentType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contenttype)[];  'accept-charset'?: string | string[];  'accept-encoding'?: [ContentCoding](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contentcoding) | [ContentCoding](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contentcoding)[];  'accept-language'?: string | string[];  'cache-control'?: string | string[];  'cookie'?: string | string[];  'range'?: string | string[];  'upgrade'?: string | string[];  'user-agent'?: string;  'content-type'?: [ContentType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contenttype); } | 若键取值为[k: string]: string | string[] | undefined，表示值类型为一个包含一个或多个键值对的对象，其键的类型为字符，可取任意值，其值的类型为字符、字符数组或undefined。  若键取值为'authorization'，值的类型为字符，可取任意值。  若键取值为'accept'，值的类型为[ContentType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contenttype)或[ContentType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contenttype)数组，可取任意值。  若键取值为'accept-charset'，值的类型为字符或字符数组，可取任意值。  若键取值为'accept-encoding'，值的类型为[ContentCoding](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contentcoding)或[ContentCoding](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contentcoding)数组，可取任意值。  若键取值为'accept-language'，值的类型为字符或字符数组，可取任意值。  若键取值为'cache-control'，值的类型为字符或字符数组，可取任意值。  若键取值为'cookie'，值的类型为字符或字符数组，可取任意值。  若键取值为'range'，值的类型为字符或字符数组，可取任意值。  若键取值为'upgrade'，值的类型为字符或字符数组，可取任意值。  若键取值为'user-agent'，值的类型为字符，可取任意值。  若键取值为'content-type'，值的类型为[ContentType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contenttype)，可取任意值。当此项不存在或为空字符串时，系统将根据[RequestContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#requestcontent)配置默认的内容类型。若不希望使用默认内容类型，可以传入单个空格。 |

## SendingPausePolicy

PhonePC/2in1TabletTVWearable

暂停发送流程的策略。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'timeout' | 否 | 否 | 策略类型。用来表示这是暂停发送流程的策略。 |
| timeoutMs | number | 否 | 否 | 超时时间，如果超过了该时间，应用还没有给框架数据，就会暂停请求，单位为毫秒。  取值范围：1~1000。  默认值为 0。 |

## NetworkInputQueue

PhonePC/2in1TabletTVWearable

const NetworkInputQueue: NetworkInputQueueConstructor

通过 new NetworkInputQueue()来创建一个[INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

## NetworkInputQueueConstructor

PhonePC/2in1TabletTVWearable

NetworkInputQueueConstructor是一个[INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue)的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### new

PhonePC/2in1TabletTVWearable

new (): INetworkInputQueue

创建一个[INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue) | 返回一个同步写队列对象。 |

### new

PhonePC/2in1TabletTVWearable

new (maxSize: number): INetworkInputQueue

创建一个[INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| maxSize | number | 是 | 队列大小，表示可写入的最大字节数。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue) | 返回一个同步写队列对象。 |

### new

PhonePC/2in1TabletTVWearable

new (maxSize: number, pausePolicyOverride: SendingPausePolicy): INetworkInputQueue

创建一个[INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| maxSize | number | 是 | 队列大小，表示可写入的最大字节数。 |
| pausePolicyOverride | [SendingPausePolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#sendingpausepolicy) | 是 | 请求的发送暂停策略。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue) | 返回一个同步写队列对象。 |

## INetworkInputQueue

PhonePC/2in1TabletTVWearable

INetworkInputQueue是用于写请求体的同步写队列。通过new [NetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#networkinputqueue)()来构造。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### write

PhonePC/2in1TabletTVWearable

write(buffer: string | ArrayBuffer): void

将一段数据写入队列当中，框架的IO线程会在合适的时候把该数据发送出去。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| buffer | string | ArrayBuffer | 是 | 要发送的请求。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900990](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900990-内存不足) | Out of memory. |

### close

PhonePC/2in1TabletTVWearable

close(): void

关闭此同步写队列，IO线程不再从该队列读取数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

### getFreeSpace

PhonePC/2in1TabletTVWearable

getFreeSpace(): number

获取剩余可写空间。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| number | 获取剩余可写空间。 |

## RequestContent

PhonePC/2in1TabletTVWearable

type RequestContent = RawDataContent | Form | MultipartForm | GetDataCallback | UploadFromFile | UploadFromStream | INetworkInputQueue

RequestContent是HTTP模块中的一种类型，代表HTTP请求的内容。它可以有多种形式，可以灵活指定请求中要发送的数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| [RawDataContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#rawdatacontent) | ArkTs的基本类型的数据。 |
| [Form](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#form) | HTTP简单的表格数据。 |
| [MultipartForm](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartform) | HTTP多部分表格数据。 |
| [GetDataCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#getdatacallback) | 获取任意数据的回调方法的类型，其入参为数据最大字节数。 |
| [UploadFromStream](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#uploadfromstream) | UploadFromStream表示以流的形式进行上传操作。  **起始版本：** 5.0.0(12) |
| [UploadFromFile](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#uploadfromfile) | UploadFromFile表示一种文件上传的方式，允许客户端将本地计算机上的文件上传到服务器。  **起始版本：** 5.0.0(12) |
| [INetworkInputQueue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inetworkinputqueue) | INetworkInputQueue是用于写请求体的同步写队列。  **起始版本：** 5.0.0(12) |

## Form

PhonePC/2in1TabletTVWearable

HTTP简单的表格数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

### 属性

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| fields | [FormFields](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfields) | 否 | 否 | HTTP简单表单数据字段，类型为表单字段类型。 |
| keys | string[] | 否 | 是 | 指定表单中key的发送顺序。  指定后按keys列表的先后顺序发送（不在列表中的key不发送）；不指定默认按各个key的hash顺序发送。  **起始版本：** 6.0.1(21) |

### constructor

PhonePC/2in1TabletTVWearable

constructor(fields: FormFields)

提供用于创建Form对象的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| fields | [FormFields](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfields) | 是 | HTTP简单表单数据字段，类型为表单字段类型。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. let headers: rcp.RequestHeaders = {
4. "accept": "application/json"
5. };
6. let configuration: rcp.Configuration = {
7. transfer: {
8. timeout: { connectMs: 60000, transferMs: 60000 }
9. }
10. };
11. let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
12. let transferRange: rcp.TransferRange = { from: 100, to: 200 };

14. const simpleForm = new rcp.Form({
15. "key1": "value1",
16. "key2": ["valueList0", "valueList1"],
17. });
18. simpleForm.keys = ["key2", "key1"];
19. let req = new rcp.Request("http://example.com", "POST", headers, simpleForm, cookies, transferRange, configuration);
20. req.content = simpleForm;
```

## MultipartForm

PhonePC/2in1TabletTVWearable

HTTP多部分表格数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

### 属性

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| fields | [MultipartFormFields](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartformfields) | 否 | 否 | 表示多部分表单数据，其中值为多表单字段类型。 |
| boundary | string | 否 | 是 | 多表单中自定义分隔符，开发者可在上传多表单时通过自定义boundary字段实现对表单数据的准确分隔与传输。boundary长度不超过46字符，否则抛出参数错误码。  **起始版本：** 5.1.0(18) |
| keys | string[] | 否 | 是 | 定义多部分表单中的键顺序。  指定后按keys列表的先后顺序发送（不在列表中的key不发送）；不指定默认按各个key的hash顺序发送。  **起始版本：** 6.0.1(21) |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/errorcode-universal#section401-参数检查失败) | Parameter error. |

### constructor

PhonePC/2in1TabletTVWearable

constructor(fields: MultipartFormFields)

提供用于创建MultipartForm对象的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| fields | [MultipartFormFields](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartformfields) | 是 | 表示多部分表单数据，其中值为多表单字段类型。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. let headers: rcp.RequestHeaders = {
4. "accept": "application/json"
5. };
6. let configuration: rcp.Configuration = {
7. transfer: {
8. timeout: { connectMs: 60000, transferMs: 60000 }
9. }
10. };
11. let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
12. let transferRange: rcp.TransferRange = { from: 100, to: 200 };

14. const multiForm = new rcp.MultipartForm({
15. "key1": "value1",
16. "key2": ["valueList0", "valueList1"],
17. "key3": {
18. contentType: "text/plain",
19. remoteFileName: "RemoteFileName",
20. contentOrPath: "/file/to/Path",
21. },
22. });
23. multiForm.keys = ["key3", "key1", "key2"];
24. let req = new rcp.Request("http://example.com", "POST", headers, multiForm, cookies, transferRange, configuration);
25. req.content = multiForm;
```

### constructor

PhonePC/2in1TabletTVWearable

constructor(fields: MultipartFormFields, boundary: string)

提供用于创建MultipartForm对象的构造函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.1.0(18)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| fields | [MultipartFormFields](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartformfields) | 是 | 表示多部分表单数据，其中值为多表单字段类型。 |
| boundary | string | 是 | 多表单中自定义分隔符，开发者可在上传多表单时通过自定义boundary字段实现对表单数据的准确分隔与传输。若boundary长度超过46字符，抛出参数错误码。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. let headers: rcp.RequestHeaders = {
4. "accept": "application/json"
5. };
6. let configuration: rcp.Configuration = {
7. transfer: {
8. timeout: { connectMs: 60000, transferMs: 60000 }
9. }
10. };
11. let cookies: rcp.RequestCookies = { 'name1': 'value1', 'name2': 'value2' };
12. let transferRange: rcp.TransferRange = { from: 100, to: 200 };
13. let Boundary: string = "--MULTIPARTFORM BEGIN AND END BOUNDARY"

15. const multiForm = new rcp.MultipartForm({
16. "key1": "value1",
17. "key2": ["valueList0", "valueList1"],
18. "key3": {
19. contentType: "text/plain",
20. remoteFileName: "RemoteFileName",
21. contentOrPath: "/file/to/Path",
22. },
23. }, Boundary)
24. multiForm.keys = ["key3", "key1", "key2"];

26. let req = new rcp.Request("http://example.com", "POST", headers, multiForm, cookies, transferRange, configuration);
27. req.content = multiForm;
```

## MultipartFormFields

PhonePC/2in1TabletTVWearable

type MultipartFormFields = { [k: string]: MultipartFormFieldValue | MultipartFormFieldValue[]; }

HTTP多部分表单数据字段。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| { [k: string]: [MultipartFormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartformfieldvalue) | [MultipartFormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartformfieldvalue)[] } | 表示值的类型为一个或者多个多部分表单数据字段值，值的类型为[MultipartFormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartformfieldvalue)或[MultipartFormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#multipartformfieldvalue)的数组，可取任意值。 |

## MultipartFormFieldValue

PhonePC/2in1TabletTVWearable

type MultipartFormFieldValue = FormFieldValue | FormFieldFileValue

HTTP多部分表单数据字段值。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| [FormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfieldvalue) | 表示值的类型为[FormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfieldvalue)，HTTP简单表单数据字段值。 |
| [FormFieldFileValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfieldfilevalue) | 表示值的类型为[FormFieldFileValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfieldfilevalue)，文件表单数据接口。 |

## FormFields

PhonePC/2in1TabletTVWearable

type FormFields = { [k: string]: FormFieldValue | FormFieldValue[]; }

HTTP简单表单数据字段。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| { [k: string]: [FormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfieldvalue) | [FormFieldValue](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#formfieldvalue)[] } | 表示值的类型为简单表单字段或对应数组。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const simpleForm: rcp.FormFields = {
4. "key1": "value1",
5. "key2": ["valueList0", "valueList1"],
6. };
```

## FormFieldValue

PhonePC/2in1TabletTVWearable

type FormFieldValue = string | number | boolean | bigint

HTTP简单表单数据字段值。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| string | 表示字段的值是一个字符串。 |
| number | 表示字段的值是一个数字，可以是整数或浮点数。如传入的数据大于2147483647，请使用bigint类型。 |
| boolean | 表示字段的值是一个布尔值。 |
| bigint | 表示字段的值是一个大整数。使用此类型传入大于32位的整数。 |

## Path

PhonePC/2in1TabletTVWearable

type Path = string

HTTP表单数据内容中的文件路径类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| string | 表示值的类型为string，可取任意值。 |

## FileContent

PhonePC/2in1TabletTVWearable

HTTP表单数据内容中的文件内容类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| content | string | ArrayBuffer | 否 | 否 | 要发送到远程服务器的内容，可取任意值。 |

## FormFieldFileValue

PhonePC/2in1TabletTVWearable

文件表单数据接口。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| contentType | [ContentType](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#contenttype) | 否 | 是 | HTTP多部分表单数据内容类型。默认值为undefined。 |
| remoteFileName | string | 否 | 是 | 保存到远程服务器的文件名。默认值为undefined。 |
| contentOrPath | [Path](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#path) | [FileContent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#filecontent) | [GetDataCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#getdatacallback) | 否 | 否 | 要发送到远程服务器的内容或文件路径。具体允许的类型见链接。 |

**示例**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const formFieldFileValue: rcp.FormFieldFileValue = {
4. contentType: "image/png",
5. remoteFileName: "remoteFile1",
6. contentOrPath: "/path/to/file",
7. };
```

## RequestCookies

PhonePC/2in1TabletTVWearable

RequestCookies是HTTP模块中的一个接口，用于表示HTTP请求中包含的cookie。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| [name: string] | string | 否 | 否 | Cookies数据。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const cookies: rcp.RequestCookies = {
4. "sessionID": "abc123",
5. "userToken": "xyz789",
6. // Additional cookies can be added here
7. };
```

## TransferRange

PhonePC/2in1TabletTVWearable

设置传输数据范围。HTTP范围请求要求服务器只将HTTP消息的一部分发回客户端。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| from | number | 否 | 是 | 用于设置传输数据的起始字节。默认值为undefined。 |
| to | number | 否 | 是 | 用于设置传输数据的结束字节。默认值为undefined。 |

## Response

PhonePC/2in1TabletTVWearable

HTTP请求的响应数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

### 属性

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 是 | 否 | 收到此响应的相关HTTP请求内容。 |
| statusCode | number | 是 | 否 | HTTP请求的结果代码。如果回调函数成功执行，将返回ResponseCode中定义的结果代码。否则，将在AsyncCallback中的error字段中返回错误代码。 |
| headers | [ResponseHeaders](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responseheaders) | 是 | 否 | 响应头。 |
| effectiveUrl | [URL](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#url) | 是 | 是 | 重定向后请求的有效URL。默认值为undefined。 |
| body | ArrayBuffer | 是 | 是 | 响应内容根据响应头中的Content-type返回。响应内容必须与服务器返回的数据类型相同。默认最大下载字节数是50M。如果超过50M，为了防止内存溢出，请通过[OnDataReceive](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ondatareceive)来流式接收数据。 |
| downloadedTo | [DownloadedTo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadedto) | 是 | 是 | 内容下载的路径。在使用下载至文件对象和文件标识符两种方式时，默认情况下，并未设置回调信息。  **起始版本：** 5.0.0(12) |
| debugInfo | [DebugInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#debuginfo)[] | 是 | 是 | 与响应相关联的调试信息。默认值为undefined。 |
| timeInfo | [TimeInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinfo) | 是 | 是 | HTTP请求各阶段的定时信息。默认值为undefined。 |
| cookies | [ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie)[] | 是 | 是 | 响应中的Cookie数组。 |
| httpVersion | [HttpVersion](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpversion) | 是 | 是 | HTTP的版本。  **起始版本：** 5.0.0(12) |
| reasonPhrase | string | 是 | 是 | HTTP响应状态行的reasonPhrase，提供与数字状态代码相关的文本描述。  **起始版本：** 5.0.0(12) |
| cacheInfo | [CacheInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cacheinfo) | 是 | 是 | 缓存信息，包含缓存已存在时长、原始HTTP请求ID信息。当HTTP响应从缓存中获取时，该属性有值，否则为undefined。  **起始版本：** 6.0.0(20) |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. // 以下为如何修改response，仅供参考
4. interface ChangeableResponse {
5. request: rcp.Request;
6. statusCode: number;
7. headers: rcp.ResponseHeaders;
8. effectiveUrl?: rcp.URL;
9. body?: ArrayBuffer;
10. downloadedTo?: rcp.DownloadedTo;
11. debugInfo?: rcp.DebugInfo[];
12. timeInfo?: rcp.TimeInfo;
13. cookies?: rcp.ResponseCookie[];
14. httpVersion?: rcp.HttpVersion;
15. reasonPhrase?: string;
16. cacheInfo?: rcp.CacheInfo;
17. }

19. async function TestRcp() {
20. const session = rcp.createSession();
21. const resp = await session.get('https://www.example.com');
22. const changeableResponse = resp as ChangeableResponse;
23. changeableResponse.headers = HEADERS // 此处请自行定义
24. changeableResponse.statusCode = STATUSCODE // 此处请自行定义
25. }
```

### toString

PhonePC/2in1TabletTVWearable

toString(): string | null

将响应正文转换为字符串。如果转换失败，则返回空值。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| string | null | 如果HTTP响应体不是UTF-8格式，则返回UTF-8格式字符串；或者返回null。 |

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. const request = new rcp.Request("https://www.example.com");
6. session.fetch(request).then((response: rcp.Response) => {
7. if (response) {
8. console.info(`response: ${response.toString()}`);
9. }
10. }).catch((err: BusinessError) => {
11. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
12. });
```

### toJSON

PhonePC/2in1TabletTVWearable

toJSON(): object | null

返回默认的JSON反序列化结果，如需要定制JSON反序列化方式，请参考[JSON解析与生成](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-json)。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| object | null | 如果没有异常，则返回带有toString()的JSON格式字符串，toJSON是针对body的，如果body不是JSON那么返回值会是null。 |

**示例：**



```
1. import { BusinessError } from '@kit.BasicServicesKit';
2. import { rcp } from '@kit.RemoteCommunicationKit';

4. const session = rcp.createSession();
5. const request = new rcp.Request("https://www.example.com");
6. session.fetch(request).then((response: rcp.Response) => {
7. if (response) {
8. console.info(`response: ${response.toJSON()}`);
9. }
10. }).catch((err: BusinessError) => {
11. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
12. });
```

### toJSON

PhonePC/2in1TabletTVWearable

toJSON(param: json.ParseOptions): object | null

根据解析配置对[toString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tostring)方法返回的字符串进行JSON解析，并返回解析后的结果。详情请参阅[JSON解析与生成](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-json)的详细介绍。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.1.0(23)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| param | [json.ParseOptions](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-json#parseoptions) | 是 | 解析配置项。支持定义处理BigInt的模式。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| object | null | 对通过[toString()](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tostring)方法转换后的字符串进行JSON解析的结果，如果解析过程中发生异常，则返回null。toJSON方法用于处理body，当body不是JSON格式时，返回值同样为null。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { JSON } from '@kit.ArkTS';
3. import { BusinessError } from '@kit.BasicServicesKit';

5. const session = rcp.createSession();
6. const request = new rcp.Request("https://www.example.com");
7. session.fetch(request).then((response: rcp.Response) => {
8. if (response) {
9. const obj = response.toJSON({ bigIntMode: JSON.BigIntMode.PARSE_AS_BIGINT }); // 此处仅为示意，实际response的body应为JSON格式，且可能包含大整型数据
10. console.info(`response json result: ${JSON.stringify(obj)}`);
11. }
12. }).catch((err: BusinessError) => {
13. console.error(`err: error code is ${err.code}, error data is ${err.data}`);
14. });
```

## ResponseSendable

PhonePC/2in1TabletTVWearable

HTTP请求的响应数据，该响应数据支持Sendable。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| requestId | string | 是 | 否 | 待发送请求的序列号。 |
| statusCode | number | 是 | 否 | HTTP请求的结果码。 |
| headers | [ResponseHeaders](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responseheaders) | 是 | 否 | 响应头。 |
| effectiveUrl | string | 是 | 是 | 重定向后请求的有效URL字符串。默认值为undefined。 |
| body | ArrayBuffer | 是 | 是 | 响应内容将依据响应头中的content-type返回，并且必须与服务器返回的数据类型相匹配。 |
| downloadedTo | [DownloadedTo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#downloadedto) | 是 | 是 | 内容下载的路径，在使用下载至文件对象和文件标识符两种方式时，默认情况下，不设置回调信息。 |
| debugInfo | [DebugInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#debuginfo)[] | 是 | 是 | 与响应相关联的调试信息，默认值为undefined。 |
| timeInfo | [TimeInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinfo) | 是 | 是 | HTTP请求各阶段的定时信息，默认值为undefined。 |
| cookies | [ResponseCookie](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecookie)[] | 是 | 是 | 响应中的Cookie数组。 |
| httpVersion | [HttpVersion](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpversion) | 是 | 是 | HTTP的版本。 |
| reasonPhrase | string | 是 | 是 | 提供HTTP请求结果代码的文本描述。 |
| cacheInfo | [CacheInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cacheinfo) | 是 | 是 | 缓存信息，包含缓存已存在时长、原始HTTP请求ID信息。当HTTP响应从缓存中获取时，该属性有值，否则为undefined。 |

## ResponseHeaders

PhonePC/2in1TabletTVWearable

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[]; }

定义响应头类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| { [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[]; } | 若键取值为[k: string]: string | string[] | undefined，表示值类型为一个包含一个或多个键值对的对象，其键的类型为字符，可取任意值，其值的类型为字符、字符数组或undefined。  'accept-ranges'表示响应头accept-ranges数据。  若键的值为'allow'，值的类型为HttpMethod或者HttpMethod[]，可取任意值。  若键取值为'cache-control'，值的类型为字符串或字符串数组，可取任意值。  若键的值为'content-encoding'，值的类型为ContentCoding，可取任意值。  若键的值为'content-range'，值的类型为字符串，可取任意值。  若键的值为'content-type'，值的类型为ContentType，可取任意值。  若键的值为'date'，值的类型为字符串，可取任意值。  若键的值为'etag'，值的类型为字符串，可取任意值。  若键的值为'expires'，值的类型为字符串，可取任意值。  若键的值为'location'，值的类型为字符串，可取任意值。  若键的值为'retry-after'，值的类型为字符串，可取任意值。  若键的值为'set-cookie'，值的类型为字符串或字符串数组，可取任意值。  若键的值为'server'，值的类型为字符串，可取任意值。  若键的值为'www-authenticate'，值的类型为字符串或字符串数组，可取任意值。 |

## ResponseCookie

PhonePC/2in1TabletTVWearable

HTTP响应的cookie接口。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| name | string | 否 | 否 | cookie的名称。 |
| value | string | 否 | 是 | cookie的值。 |
| domain | string | 否 | 是 | cookie的域。 |
| path | string | 否 | 是 | cookie的路径。 |
| expires | string | 否 | 是 | cookie的过期日期。 |
| maxAge | number | 否 | 是 | cookie的最大保存时间，单位为秒。 |
| isSecure | true | 否 | 是 | 指定cookie是否只能通过安全连接发送。默认值为true。 |
| httpOnly | true | 否 | 是 | 指定cookie是否只能通过HTTP请求访问。默认值为true。 |
| sameSite | string | 否 | 是 | sameSite属性，指定何时在跨站请求中发送cookie。 |
| rawSize | number | 否 | 是 | cookie的大小。 |
| cookieAttributes | [CookieAttributes](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cookieattributes) | 否 | 是 | 响应cookie中的所有属性。 |

## DebugInfo

PhonePC/2in1TabletTVWearable

请求/响应处理调试信息的接口。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| type | [DebugEvent](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#debugevent) | 否 | 否 | 调试信息的类型。具体类型值见类型链接。 |
| data | ArrayBuffer | 否 | 否 | 调试信息的数据。 |

## HttpVersion

PhonePC/2in1TabletTVWearable

type HttpVersion = '1.0' | '1.1' | '2' | '3' | 'unknown'

HTTP的版本。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| '1.0' | 表示值的类型为字符串，'1.0'代表HTTP版本为1.0。 |
| '1.1' | 表示值的类型为字符串，'1.1'代表HTTP版本为1.1。 |
| '2' | 表示值的类型为字符串，'2'代表HTTP版本为2。 |
| '3' | 表示值的类型为字符串，'3'代表HTTP版本为3。 |
| 'unknown' | 表示值的类型为字符串'unknown'。 |

## TimeInfo

PhonePC/2in1TabletTVWearable

HTTP请求各阶段相关的时间信息的接口。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| nameLookupTimeMs | number | 否 | 否 | DNS解析所需的时间，单位为毫秒。 |
| connectTimeMs | number | 否 | 否 | 建立连接时间，单位为毫秒。 |
| tlsHandshakeTimeMs | number | 否 | 否 | 从开始到远程主机（或代理）的 TLS 握手完成的时间（以毫秒为单位）。  **起始版本：** 5.0.0(12) |
| preTransferTimeMs | number | 否 | 否 | 传输开始前的时间，单位为毫秒。 |
| startTransferTimeMs | number | 否 | 否 | 传输开始时间，单位为毫秒。 |
| totalTimeMs | number | 否 | 否 | 请求总耗时，单位为毫秒。 |
| redirectTimeMs | number | 否 | 否 | 重定向所需的时间，单位为毫秒。 |

说明

TimeInfo时间线：请求开始 （0时刻） -> nameLookupTimeMs（DNS解析）-> connectTimeMs（建立连接）-> tlsHandshakeTimeMs（TLS握手）-> preTransferTimeMs（请求业务数据发送到服务器的时间点） -> startTransferTimeMs（从服务器接收到首包数据的时间点），各时间节点所显示的时间均相对于0时刻，即从0时刻开始计时的时间。例如tlsHandshakeTimeMs为150.1ms，指从发起请求时间0开始，直到TLS握手结束所花费的时间为150.1ms。

网络请求过程中关键节点时间计算方法：

* 首包耗时：startTransferTimeMs - preTransferTimeMs
* TLS握手（不包含建连时间）耗时：tlsHandshakeTimeMs - connectTimeMs
* 接收剩余数据的耗时：totalTimeMs - startTransferTimeMs

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';

4. // 1、创建session、requestURL
5. const session = rcp.createSession();
6. const requestURL = "https://www.example.com";

8. // 2、在需要跟踪分析请求过程中各个时间段消耗的时间，请将此开关打开
9. const configuration: rcp.Configuration = {
10. tracing: {
11. collectTimeInfo: true
12. }
13. }

15. // 3、创建请求
16. const request = new rcp.Request(requestURL, "GET");
17. request.configuration = configuration;

19. // 4、使用fetch发起网络请求，request中携带上面配置好的configuration
20. session.fetch(request).then((response: rcp.Response) => {
21. // 由于timeInfo中各个参数有可能为undefined，所以需要在两个时间段做运算前添加判空操作
22. if (!response.timeInfo) {
23. console.error(`TimeInfo is undefined ${response.timeInfo}`);
24. return;
25. }
26. let remainderDataTime = response.timeInfo?.totalTimeMs - response.timeInfo?.startTransferTimeMs;
27. let firstPackageTime = response.timeInfo?.startTransferTimeMs - response.timeInfo?.preTransferTimeMs;
28. let TLSTime = response.timeInfo?.tlsHandshakeTimeMs - response.timeInfo?.connectTimeMs;

30. console.info(`首包耗时${firstPackageTime}`);
31. console.info(`TLS握手（不包含建连时间）耗时${TLSTime}`);
32. console.info(`接收剩余数据的耗时${remainderDataTime}`);
33. }).catch((err: BusinessError) => {
34. console.error(`Response err, the error code is ${err.code}, error data is ${err.data}`);
35. })
```

## CookieAttributes

PhonePC/2in1TabletTVWearable

type CookieAttributes = { [k: string]: string | undefined; }

Cookie属性类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| { [k: string]: string | undefined; } | 表示值的类型为一个包含一个或多个键值对的对象。其中键的类型为字符，可取任意值，值的类型为字符或者undefined，可取任意值。 |

## ContentType

PhonePC/2in1TabletTVWearable

type ContentType = 'application/json' | 'text/plain' | 'multipart/form-data' | 'application/octet-stream' | 'application/x-www-form-urlencoded' | (string & NonNullable<unknown>)

定义内容类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| 'application/json' | 'application/json': 表示数据内容的类型为json字符串。 |
| 'text/plain' | 'text/plain': 表示数据内容的类型为文本数据。 |
| 'multipart/form-data' | 'multipart/form-data': 表示数据内容的类型为表单数据。 |
| 'application/octet-stream' | 'application/octet-stream': 表示数据内容的类型为二进制数据流。 |
| 'application/x-www-form-urlencoded' | 'application/x-www-form-urlencoded': 表示数据内容的类型为表单数据。 |
| (string & NonNullable<unknown>) | string & NonNullable<unknown>：表示值的类型为字符，可取任意非空字符。 |

## ValidationContext

PhonePC/2in1TabletTVWearable

证书上下文。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| pemCerts | string[] | 否 | 否 | PEM格式证书。 |
| x509Certs | [X509Cert](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#x509cert)[] | 否 | 否 | X509证书对象。 |
| host | string | 否 | 否 | 建立连接的服务器的域名。 |
| ip | string | 否 | 否 | 建立连接的服务器的IP地址。 |

## ValidationCallback

PhonePC/2in1TabletTVWearable

type ValidationCallback = (context: ValidationContext) => boolean | Promise<boolean>

自定义证书校验函数。可以使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| context | [ValidationContext](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#validationcontext) | 是 | 表示值的类型为context，是证书上下文。 |

**返回值：**

展开

| 取值范围 | 说明 |
| --- | --- |
| boolean | 回调函数。返回true表示校验成功；返回false表示校验失败。 |
| Promise<boolean> | Promise对象。返回true表示校验成功；返回false表示校验失败。 |

## TlsV13SpecificCipherSuite

PhonePC/2in1TabletTVWearable

type TlsV13SpecificCipherSuite = 'TLS\_AES\_128\_GCM\_SHA256' | 'TLS\_AES\_256\_GCM\_SHA384' | 'TLS\_CHACHA20\_POLY1305\_SHA256'

TLS1.3及以上版本支持的加密套件。本框架有内置的优先顺序，且用户自身的选择也会被记录。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| 'TLS\_AES\_128\_GCM\_SHA256' | 表示值的类型为字符，可取'TLS\_AES\_128\_GCM\_SHA256'。 |
| 'TLS\_AES\_256\_GCM\_SHA384' | 表示值的类型为字符，可取'TLS\_AES\_256\_GCM\_SHA384'。 |
| 'TLS\_CHACHA20\_POLY1305\_SHA256' | 表示值的类型为字符，可取'TLS\_CHACHA20\_POLY1305\_SHA256'。 |

## TlsV12SpecificCipherSuite

PhonePC/2in1TabletTVWearable

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';

TLS1.2及以上版本支持的加密套件。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| 'TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256' | 表示值的类型为字符串，可取'TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_GCM\_SHA256'。 |
| 'TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256' | 表示值的类型为字符串，可取'TLS\_ECDHE\_RSA\_WITH\_AES\_128\_GCM\_SHA256'。 |
| 'TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384' | 表示值的类型为字符串，可取'TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_GCM\_SHA384'。 |
| 'TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384' | 表示值的类型为字符串，可取'TLS\_ECDHE\_RSA\_WITH\_AES\_256\_GCM\_SHA384'。 |
| 'TLS\_ECDHE\_ECDSA\_WITH\_CHACHA20\_POLY1305\_SHA256' | 表示值的类型为字符串，可取'TLS\_ECDHE\_ECDSA\_WITH\_CHACHA20\_POLY1305\_SHA256'。 |
| 'TLS\_ECDHE\_RSA\_WITH\_CHACHA20\_POLY1305\_SHA256' | 表示值的类型为字符串，可取'TLS\_ECDHE\_RSA\_WITH\_CHACHA20\_POLY1305\_SHA256'。 |
| 'TLS\_RSA\_WITH\_AES\_128\_GCM\_SHA256' | 表示值的类型为字符串，可取'TLS\_RSA\_WITH\_AES\_128\_GCM\_SHA256'。 |
| 'TLS\_RSA\_WITH\_AES\_256\_GCM\_SHA384' | 表示值的类型为字符串，可取'TLS\_RSA\_WITH\_AES\_256\_GCM\_SHA384'。 |

## TlsV10SpecificCipherSuite

PhonePC/2in1TabletTVWearable

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'

TLS1.0及以上版本支持的加密套件。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| 'TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA' | 表示值的类型为字符串，可取'TLS\_ECDHE\_ECDSA\_WITH\_AES\_128\_CBC\_SHA'。 |
| 'TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA' | 表示值的类型为字符串，可取'TLS\_ECDHE\_RSA\_WITH\_AES\_128\_CBC\_SHA'。 |
| 'TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA' | 表示值的类型为字符串，可取'TLS\_ECDHE\_ECDSA\_WITH\_AES\_256\_CBC\_SHA'。 |
| 'TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA' | 表示值的类型为字符串，可取'TLS\_ECDHE\_RSA\_WITH\_AES\_256\_CBC\_SHA'。 |
| 'TLS\_RSA\_WITH\_AES\_128\_CBC\_SHA' | 表示值的类型为字符串，可取'TLS\_RSA\_WITH\_AES\_128\_CBC\_SHA'。 |
| 'TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA' | 表示值的类型为字符串，可取'TLS\_RSA\_WITH\_AES\_256\_CBC\_SHA'。 |
| 'TLS\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA' | 表示值的类型为字符串，可取'TLS\_RSA\_WITH\_3DES\_EDE\_CBC\_SHA'。 |

## CipherSuite

PhonePC/2in1TabletTVWearable

type CipherSuite = TlsV13CipherSuite

加密套件声明函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| [TlsV13CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv13ciphersuite) | 表示值的类型为[TlsV13CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv13ciphersuite)。 |

## TlsV13CipherSuite

PhonePC/2in1TabletTVWearable

type TlsV13CipherSuite = TlsV12CipherSuite | TlsV13SpecificCipherSuite

TLS1.3的加密套件声明函数，支持TLS1.3版本，兼容TLS1.2版本。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| [TlsV12CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv12ciphersuite) | 表示值的类型为[TlsV12CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv12ciphersuite)。 |
| [TlsV13SpecificCipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv13specificciphersuite) | 表示值的类型为[TlsV13SpecificCipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv13specificciphersuite)。 |

## TlsV12CipherSuite

PhonePC/2in1TabletTVWearable

type TlsV12CipherSuite = TlsV11CipherSuite | TlsV12SpecificCipherSuite

TLS1.2的加密套件声明函数，支持TLS1.2版本，兼容TLS1.1版本。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| [TlsV11CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv11ciphersuite) | 表示值的类型为[TlsV11CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv11ciphersuite)。 |
| [TlsV12SpecificCipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv12specificciphersuite) | 表示值的类型为[TlsV12SpecificCipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv12specificciphersuite)。 |

## TlsV11CipherSuite

PhonePC/2in1TabletTVWearable

type TlsV11CipherSuite = TlsV10CipherSuite

TLS1.1的加密套件声明函数，与TLS1.0相同。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| [TlsV10CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv10ciphersuite) | 表示值的类型为[TlsV10CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv10ciphersuite)。 |

## TlsV10CipherSuite

PhonePC/2in1TabletTVWearable

type TlsV10CipherSuite = TlsV10SpecificCipherSuite

TLS1.0的加密套件声明函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 类型 | 说明 |
| --- | --- |
| [TlsV10SpecificCipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv10specificciphersuite) | 表示值的类型为[TlsV10SpecificCipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv10specificciphersuite)。 |

## TlsV13Option

PhonePC/2in1TabletTVWearable

TLS1.3选择器，用来选择Tls的使用版本，以及配套加密套件。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| tlsVersion | 'TlsV1.3' | 否 | 否 | TLS版本为"TlsV1.3"。 |
| cipherSuite | [TlsV13CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv13ciphersuite)[] | 否 | 是 | TLS1.3版本对应的加密套件。 |

## TlsV12Option

PhonePC/2in1TabletTVWearable

TLS1.2选择器，用来选择Tls的使用版本，以及配套加密套件。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| tlsVersion | 'TlsV1.2' | 否 | 否 | TLS版本为'TlsV1.2'。 |
| cipherSuite | [TlsV12CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv12ciphersuite)[] | 否 | 是 | TLS1.2版本对应的加密套件。 |

## TlsV11Option

PhonePC/2in1TabletTVWearable

TLS1.1选择器，用来选择Tls的使用版本，以及配套加密套件。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| tlsVersion | 'TlsV1.1' | 否 | 否 | TLS版本为'TlsV1.1'。 |
| cipherSuite | [TlsV11CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv11ciphersuite)[] | 否 | 是 | TLS1.1版本对应的加密套件。 |

## TlsV10Option

PhonePC/2in1TabletTVWearable

TLS1.0选择器，用来选择Tls的使用版本，以及配套加密套件。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| tlsVersion | 'TlsV1.0' | 否 | 否 | TLS版本为'TlsV1.0'。 |
| cipherSuite | [TlsV10CipherSuite](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#tlsv10ciphersuite)[] | 否 | 是 | TLS1.0版本对应的加密套件。 |

## ContentCoding

PhonePC/2in1TabletTVWearable

type ContentCoding = 'aes128gcm' | 'br' | 'compress' | 'deflate' | 'exi' | 'gzip' | 'pack200-gzip' | 'x-compress' | 'x-gzip' | 'zstd' | (string & NonNullable<unknown>)

预定义内容编码类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 取值范围 | 说明 |
| --- | --- |
| 'aes128gcm' | 表示使用AES-128-GCM加密算法对内容进行编码，用于对称加密。 |
| 'br' | 表示使用Brotli算法对内容进行编码，适用于需要高压缩比的场景，如网页、文档等。 |
| 'compress' | 表示使用Unix compress算法对内容进行编码。 |
| 'deflate' | 表示使用DEFLATE算法对内容进行编码，适用于需要高压缩比和较快压缩速度的场景。 |
| 'exi' | 表示使用XML扩展格式（EXI）对内容进行编码，适用于需要高压缩比的XML数据传输。 |
| 'gzip' | 表示使用GZIP算法对内容进行编码，广泛用于Web服务器和应用中。 |
| 'pack200-gzip' | 表示使用Pack200和GZIP算法对内容进行编码。 |
| 'x-compress' | 表示使用Zlib的compress方法对内容进行编码。 |
| 'x-gzip' | 表示使用Zlib的gzip方法对内容进行编码，gzip方法使用DEFLATE压缩算法，提供了高压缩比和较快压缩速度。 |
| 'zstd' | 表示使用Zstandard算法对内容进行编码，适用于需要高压缩比的场景，如数据库、文件压缩等。 |
| (string & NonNullable<unknown>) | 用以确保ContentCoding类型的值必须是非空字符串。 |

## ResponseValidationCallback

PhonePC/2in1TabletTVWearable

type ResponseValidationCallback = (response: Response) => boolean | Promise<boolean>

响应校验回调函数。可以使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| response | [Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response) | 是 | 框架传入的响应，即需要进行校验的响应。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| boolean | 回调函数。返回true表示校验成功；返回false表示校验失败。 |
| Promise<boolean> | Promise对象。返回true表示校验成功；返回false表示校验失败。 |

## ProcessingConfiguration

PhonePC/2in1TabletTVWearable

请求处理配置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| validateResponse | 'default' | [ResponseValidationCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsevalidationcallback) | 否 | 是 | 默认不处理。或者使用[ResponseValidationCallback](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsevalidationcallback)对响应进行校验。 |

## GetDataCallback

PhonePC/2in1TabletTVWearable

type GetDataCallback = (maxSize: number) => ArrayBuffer | Promise<ArrayBuffer>

发送数据时触发的回调，用于获取用来发送的数据，其入参为数据最大字节数。可以使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| maxSize | number | 是 | 数据最大字节数。  返回值为ArrayBuffer或使用Promise异步回调的方法，可取任意值。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| ArrayBuffer | 回调函数，返回用于发送的数据。 |
| Promise<ArrayBuffer> | Promise对象，返回用于发送的数据。  **说明：** 5.0.0(12)新增返回值Promise<ArrayBuffer>。 |

## DynamicExclusionRule

PhonePC/2in1TabletTVWearable

type DynamicExclusionRule = (url: URLOrString) => boolean

返回是否要从代理中排除入参的URL的回调函数类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | 表示URL对象或表示URL的字符串的并集类型。  表示入参的类型为[URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring)，返回值为boolean的方法。为true，代表主机使用代理，false则代表未使用。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| boolean | 返回一个boolean类型值，为true，代表主机使用代理，false则代表未使用。 |

## StaticDnsRule

PhonePC/2in1TabletTVWearable

StaticDnsRule接口表示一个单独的静态DNS规则，将特定的IP地址与主机名和端口相关联。此配置是StaticDnsRule接口的一部分，用于自定义DNS映射。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| host | string | 否 | 否 | 应用静态DNS规则的主机名。 |
| port | number | 否 | 否 | 应用静态DNS规则的端口号。范围是[0, 65535]。 |
| ipAddresses | [IpAddress](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ipaddress)[] | 否 | 否 | 要与指定的主机名和端口关联的IP地址阵列。 |

## StaticDnsRules

PhonePC/2in1TabletTVWearable

type StaticDnsRules = StaticDnsRule[]

允许开发者定义静态DNS规则，将特定的IP地址与主机名和端口关联起来。此配置适用于特定域和端口需要自定义IP映射的情况。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| [StaticDnsRule](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#staticdnsrule)[] | 表示值的类型为[StaticDnsRule](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#staticdnsrule)数组。 |

## DynamicDnsRule

PhonePC/2in1TabletTVWearable

type DynamicDnsRule = (host: string, port: number) => IpAddress[]

一个可以根据hostname和port直接返回IP地址的函数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| host | string | 是 | 指定的主机名。 |
| port | number | 是 | 指定的端口。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [IpAddress](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ipaddress)[] | 一个IP地址数组。 |

## WebProxy

PhonePC/2in1TabletTVWearable

WebProxy接口使开发者能够在[ProxyConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#proxyconfiguration)中配置自定义代理时定义自定义代理设置。它允许指定代理URL、排除和其他安全配置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 否 | 否 | 自定义代理的URL。 |
| createTunnel | 'auto' | 'always' | 否 | 是 | 用于控制何时创建代理隧道。隧道是指将HTTP CONNECT请求发送到代理，要求其连接到一个特定端口号上的远程主机，然后流量通过代理。默认值为'auto'。  'auto'表示为HTTPS创建隧道，而不是为HTTP创建。  'always'表示始终创建隧道。 |
| exclusions | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring)[] | [DynamicExclusionRule](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#dynamicexclusionrule) | 否 | 是 | 要从代理中排除的URL （例如："http://exclude.example.com"或["http://exclude1.com", "http://exclude2.com"]）。默认值为undefined。 |
| security | [SecurityConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#securityconfiguration) | 否 | 是 | 设置代理安全配置。默认值为undefined。 |

## InfoToCollect

PhonePC/2in1TabletTVWearable

InfoToCollect接口可以帮助开发者收集信息事件。收集到的信息事件会在[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)的debugInfo字段中返回。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| textual | boolean | 否 | 是 | 是否收集文本信息事件。默认值为false。 |
| incomingHeader | boolean | 否 | 是 | 是否收集传入的header信息事件。默认值为false。 |
| outgoingHeader | boolean | 否 | 是 | 是否收集传出的header信息事件。默认值为false。 |
| incomingData | boolean | 否 | 是 | 是否收集传入的数据信息事件。默认值为false。 |
| outgoingData | boolean | 否 | 是 | 是否收集传出数据信息事件。默认值为false。 |
| incomingSslData | boolean | 否 | 是 | 是否收集传入的SSL/TLS数据信息事件。默认值为false。 |
| outgoingSslData | boolean | 否 | 是 | 是否收集传出的SSL/TLS数据信息事件。默认值为false。 |
| srcAddr | boolean | 否 | 是 | 客户端地址。  true：收集客户端地址及端口号。  false：不收集客户端地址及端口号。  默认值是false。  **起始版本：** 6.0.0(20) |
| dstAddr | boolean | 否 | 是 | 服务器地址。  true：收集服务器地址及端口号。  false：不收集服务器地址及端口号。  默认值是false。  **起始版本：** 6.0.0(20) |
| redirectCount | boolean | 否 | 是 | 是否收集重定向次数。  true：收集重定向次数。  false：不收集重定向次数。  默认值为false。  **起始版本：** 6.1.0(23) |

说明

此项开启后会占用内存，建议仅在开发调试阶段使用。

## HttpEventsHandler

PhonePC/2in1TabletTVWearable

HttpEventsHandler接口使开发者能够定义自定义逻辑，用于处理会话中HTTP请求/响应过程中的各种操作。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| onDataReceive | [OnDataReceive](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ondatareceive) | 否 | 是 | 当接收到HTTP响应正文的一部分时调用的回调。默认为undefined。当开发者需要请求超过50M字节的数据时，使用此回调接受数据。使用后，返回的[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)对象的body字段将不再含有数据。 |
| onUploadProgress | [OnUploadProgress](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#onuploadprogress) | 否 | 是 | 用于在响应期间处理上传进度的回调。默认为undefined。 |
| onDownloadProgress | [OnDownloadProgress](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ondownloadprogress) | 否 | 是 | 用于在响应期间处理下载进度的的回调。默认为undefined。 |
| onHeaderReceive | [OnHeaderReceive](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#onheaderreceive) | 否 | 是 | 用于在响应期间处理接收到的headers的回调。默认为undefined。 |
| onDataEnd | [OnDataEnd](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ondataend) | 否 | 是 | 数据传输完成时触发的回调。默认为undefined。 |
| onCanceled | [OnCanceled](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#oncanceled) | 否 | 是 | 取消请求/响应时触发的回调。默认为undefined。 |
| onTimeInfo | [OnTimeInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#ontimeinfo) | 否 | 是 | HTTP请求失败/成功时触发的回调。默认为undefined。  **起始版本：** 5.0.3(15) |
| onStatusCodeReceive | [OnStatusCodeReceive](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#onstatuscodereceive) | 否 | 是 | 用于在响应期间处理接收到的状态码的回调。默认为undefined。  **起始版本：** 6.0.0(20) |

## Timeout

PhonePC/2in1TabletTVWearable

配置HTTP请求的超时值，允许开发者定义连接和传输数据所允许的最长时间。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| connectMs | number | 否 | 是 | 允许建立连接的最长时间（以毫秒为单位）。如果连接过程超过这个时间限制，连接将被认为超时。默认值为60000。 |
| transferMs | number | 否 | 是 | 允许传输数据的最长时间（以毫秒为单位）。如果数据传输过程中超过这个时间限制，传输将被认为超时。默认值为60000。 |
| inactivityMs | number | 否 | 是 | 允许在没有数据传输或连接活动的情况下，允许的最长时间。用于在从服务器接收数据或向服务器发送数据的时间间隔不能超过这个值的情况下，防止长时间的空闲连接。默认情况下，超时值没有设置，即不限制时间间隔。  **起始版本：** 5.0.0(12) |

## CertificatePinning

PhonePC/2in1TabletTVWearable

证书锁定是校验服务器的证书的公钥SHA-256哈希值是否与设置的值匹配。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.0(12)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'public-key' | 否 | 否 | 证书的校验类型。 |
| publicKeyHash | string | 否 | 否 | 公钥哈希值。 |
| hashAlgorithm | 'SHA-256' | 否 | 否 | 用于计算公钥哈希值的算法。 |

## SessionListener

PhonePC/2in1TabletTVWearable

定义会话监听器。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| onCanceled | [OnCanceled](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#oncanceled) | 否 | 是 | 会话取消事件的回调。会话取消时调用。默认为undefined。 |
| onClosed | [OnClosed](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#onclosed) | 否 | 是 | 会话关闭事件回调。会话关闭时调用。默认为undefined。 |

## Credential

PhonePC/2in1TabletTVWearable

凭据接口表示会话中服务器身份验证设置中使用的身份验证凭据，包括用户名和密码。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| username | string | 否 | 否 | 用于身份验证的用户名。默认值为' '。 |
| password | string | 否 | 否 | 用于身份验证的密码。默认值为' '。 |

## TlsVersion

PhonePC/2in1TabletTVWearable

type TlsVersion = 'TlsV1.0' | 'TlsV1.1' | 'TlsV1.2' | 'TlsV1.3'

安全配置项TLS允许设置的版本，可选择TLS的使用版本。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 取值范围 | 说明 |
| --- | --- |
| 'TlsV1.0' | 表示使用TLS1.0版本。 |
| 'TlsV1.1' | 表示使用TLS1.1版本。 |
| 'TlsV1.2' | 表示使用TLS1.2版本。 |
| 'TlsV1.3' | 表示使用TLS1.3版本。 |

## DebugEvent

PhonePC/2in1TabletTVWearable

type DebugEvent = 'text' | 'headerIn' | 'headerOut' | 'dataIn' | 'dataOut' | 'sslDataIn' | 'sslDataOut' | 'srcAddr' | 'dstAddr' | 'redirectCount'

定义调试事件类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| 'text' | 表示调试事件与HTTP响应的文本内容相关。 |
| 'headerIn' | 表示调试事件与HTTP响应的头部信息（在客户端接收响应时）相关。 |
| 'headerOut' | 表示调试事件与HTTP请求的头部信息（在客户端发送请求时）相关。 |
| 'dataIn' | 表示调试事件与HTTP响应的主体数据（在客户端接收响应时）相关。 |
| 'dataOut' | 表示调试事件与HTTP请求的主体数据（在客户端发送请求时）相关。 |
| 'sslDataIn' | 表示调试事件与通过SSL/TLS协议接收的HTTP响应数据相关。 |
| 'sslDataOut' | 表示调试事件与通过SSL/TLS协议发送的HTTP请求数据相关。 |
| 'srcAddr' | 表示调试事件与获取客户端地址和端口相关。  **起始版本：** 6.0.0(20) |
| 'dstAddr' | 表示调试事件与获取服务器地址和端口相关。  **起始版本：** 6.0.0(20) |
| 'redirectCount' | 表示调试事件与获取重定向次数相关。  **起始版本：** 6.1.0(23) |

## AuthenticationType

PhonePC/2in1TabletTVWearable

type AuthenticationType = 'basic' | 'ntlm' | 'digest'

此类型表示可以在会话中的服务器身份验证设置中使用的不同身份验证机制。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

展开

| 类型 | 说明 |
| --- | --- |
| 'basic' | 表示使用基本身份验证，通过将用户名和密码组合成一个字符串并进行Base64编码来进行身份验证。 |
| 'ntlm' | 表示使用NT LAN Manager身份验证。 |
| 'digest' | 表示使用HTTP摘要身份验证，通过将用户名、密码和其他信息进行哈希运算来生成认证信息。 |

## OnCanceled

PhonePC/2in1TabletTVWearable

type OnCanceled = (request?: Request) => void

此类型表示当请求或会话被取消时的回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。  **起始版本：** 6.0.0(20) |

## OnClosed

PhonePC/2in1TabletTVWearable

type OnClosed = () => void

此类型表示会话关闭时的回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

## OnDataReceive

PhonePC/2in1TabletTVWearable

type OnDataReceive = (incomingData: ArrayBuffer, request?: Request) => number | void | Promise<void>

此类型表示接收到HTTP body时的回调。当开发者需要请求超过50M字节的数据时，使用此回调接受数据。使用后，返回的[Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response)对象的body字段将不再含有数据。可以使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| incomingData | ArrayBuffer | 是 | 参数为收到HTTP数据。 |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。  **起始版本：** 6.0.0(20) |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| number | 回调函数，返回number类型数据，表示处理的字节数。 |
| void | 回调函数，无返回值。  **说明：** 5.0.0(12)版本上新增返回值void。 |
| Promise<void> | Promise对象，无返回结果。  **说明：** 5.0.0(12)版本上新增返回值Promise<void>。 |

## OnUploadProgress

PhonePC/2in1TabletTVWearable

type OnUploadProgress = (totalSize: number, transferredSize: number, request?: Request) => void

此类型表示上传进度时的回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| totalSize | number | 是 | 上传总大小。 |
| transferredSize | number | 是 | 已上传大小。 |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。  **起始版本：** 6.0.0(20) |

## OnDownloadProgress

PhonePC/2in1TabletTVWearable

type OnDownloadProgress = (totalSize: number, transferredSize: number, request?: Request) => void

此类型表示显示下载进度的回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| totalSize | number | 是 | 下载总大小。 |
| transferredSize | number | 是 | 已下载大小。 |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。  **起始版本：** 6.0.0(20) |

## OnHeaderReceive

PhonePC/2in1TabletTVWearable

type OnHeaderReceive = (headers: ResponseHeaders, request?: Request) => void

此类型表示接收到HTTP头时的回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| headers | [ResponseHeaders](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responseheaders) | 是 | 参数为HTTP响应头，返回为空。 |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。  **起始版本：** 6.0.0(20) |

## OnDataEnd

PhonePC/2in1TabletTVWearable

type OnDataEnd = (request?: Request) => void

此类型表示HTTP传输结束时的回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 4.1.0(11)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。  **起始版本：** 6.0.0(20) |

## OnTimeInfo

PhonePC/2in1TabletTVWearable

type OnTimeInfo = (timeInfo: TimeInfo, request?: Request) => void

此类型是HTTP请求成功/失败时的回调。请求成功开发者可获得请求各阶段的时间信息，请求失败可获得失败的阶段之前各阶段时间信息。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 5.0.3(15)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| timeInfo | [TimeInfo](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinfo) | 是 | HTTP各个阶段耗时。 |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。  **起始版本：** 6.0.0(20) |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';
2. import { BusinessError } from '@kit.BasicServicesKit';

4. // 1、创建session、requestURL和request。
5. const session = rcp.createSession();
6. const requestURL = "https://www.example.com";
7. const request = new rcp.Request(requestURL);

9. // 2、配置请求的configuration，设置onTimeInfo回调函数以获取网络请求相关的时间信息
10. request.configuration = {
11. tracing: {
12. httpEventsHandler: {
13. onTimeInfo: (timeInfo: rcp.TimeInfo) => {
14. console.info(`Time information for each phase in the HTTP request. ${JSON.stringify(timeInfo)}`);
15. let remainderDataTime = timeInfo?.totalTimeMs - timeInfo?.startTransferTimeMs;
16. let firstPackageTime = timeInfo?.startTransferTimeMs - timeInfo?.preTransferTimeMs;
17. let TLSTime = timeInfo?.tlsHandshakeTimeMs - timeInfo?.connectTimeMs;
18. console.info(`首包耗时${firstPackageTime}`);
19. console.info(`TLS握手（不包含建连时间）耗时${TLSTime}`);
20. console.info(`接收剩余数据的耗时${remainderDataTime}`);
21. },
22. },
23. },
24. };
25. // 3、使用 fetch 发起网络请求，请求中携带上述配置好的 configuration。
26. session.fetch(request).then((response) => {
27. if (response) {
28. console.info(`The request was successful. The statusCode of the response is ${response.statusCode}`);
29. session.close();
30. }
31. }).catch((err: BusinessError) => {
32. console.error(`Response err, the error code is ${err.code}, error data is ${err.data}`);
33. })
```

## OnStatusCodeReceive

PhonePC/2in1TabletTVWearable

type OnStatusCodeReceive = (statusCode: number, request?: Request) => void

此类型是HTTP请求成功/失败时的回调，开发者可获得响应状态码信息。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| statusCode | number | 是 | HTTP状态码。 |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 否 | 触发回调的HTTP请求。 |

## CacheControl

PhonePC/2in1TabletTVWearable

CacheControl 接口提供了一系列配置参数，开发者可通过这些参数精准控制会话中 HTTP 请求的缓存行为，包括资源缓存策略、更新机制及存储规则等。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| expirationPolicy | [TimeLimitedExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timelimitedexpirationpolicy) | 否 | 是 | 为HTTP请求所创建的缓存配置过期策略。如果设置该属性，则会覆盖HTTP响应过期策略。 |
| keepCache | boolean | 否 | 是 | 是否需要保留缓存，默认为false。该参数为true时，使用不安全的 HTTP 方法的请求（PUT，POST，或者DELETE）不会使缓存记录失效。 |
| noCache | boolean | 否 | 是 | 是否在请求头中添加no-cache，默认为false。该参数为true时，则会强制客户端在使用缓存前必须向服务器验证资源有效性（即使缓存存在）。 |
| noStore | boolean | 否 | 是 | 是否在请求头中添加no-store，默认为false。该参数为true时，则会严格禁止任何缓存存储请求或响应的内容，确保敏感数据不会被持久化。 |
| maxAge | [TimeInterval](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinterval) | 否 | 是 | 该属性指定缓存资源的有效时长，在此期间客户端可直接使用缓存而无需请求服务器。 |
| maxStale | [TimeInterval](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinterval) | 否 | 是 | 该属性允许客户端接受已过期但未超过指定时间的缓存资源，提升数据可用性。 |
| minFresh | [TimeInterval](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinterval) | 否 | 是 | 该属性要求服务器返回的响应在指定时间内保持新鲜，确保资源短期内不过期。 |
| noTransform | boolean | 否 | 是 | 是否在请求头中添加no-transform，默认为false。该参数为true时，则会禁止缓存服务器对响应内容进行任何转换（如压缩），保证内容与原始响应一致。 |
| onlyIfCached | boolean | 否 | 是 | 是否在请求头中添加only-if-cached，默认为false。该参数为true时，则会强制客户端仅使用缓存资源，若缓存不存在则直接失败（不发起网络请求）。 |

## CacheInfo

PhonePC/2in1TabletTVWearable

缓存信息，包含该缓存对应的原始HTTP请求ID和已存在时长。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| originalRequestId | string | 否 | 否 | 创建该缓存时的HTTP请求ID。 |
| age | [TimeInterval](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinterval) | 否 | 否 | 缓存已存在时长。 |

## ExpirationPolicy

PhonePC/2in1TabletTVWearable

type ExpirationPolicy = NeverExpirationPolicy | TimeLimitedExpirationPolicy

缓存过期策略。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 类型 | 说明 |
| --- | --- |
| [NeverExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#neverexpirationpolicy) | 永不过期类型过期策略。 |
| [TimeLimitedExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timelimitedexpirationpolicy) | 时间限制类型过期策略。 |

## NeverExpirationPolicy

PhonePC/2in1TabletTVWearable

缓存记录永不过期的过期策略。缓存记录会一直停留在缓存中，直到超过缓存大小限制。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'never' | 否 | 否 | 策略类型。用来表示这是永不过期的过期策略。 |

## TimeLimitedExpirationPolicy

PhonePC/2in1TabletTVWearable

type TimeLimitedExpirationPolicy = AbsoluteTimeExpirationPolicy | RelativeTimeExpirationPolicy | SlidingTimeExpirationPolicy

时间限制类型过期策略。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 类型 | 说明 |
| --- | --- |
| [AbsoluteTimeExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#absolutetimeexpirationpolicy) | 绝对时间过期策略。到达指定时间，该缓存记录过期。 |
| [RelativeTimeExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#relativetimeexpirationpolicy) | 相对时间过期策略。经过指定的时间间隔后，该缓存记录过期。 |
| [SlidingTimeExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#slidingtimeexpirationpolicy) | 滑动时间过期策略。指定的时间间隔期间，若无任何访问，该缓存记录过期；若有访问，则重置过期时间。 |

## AbsoluteTimeExpirationPolicy

PhonePC/2in1TabletTVWearable

绝对时间过期策略。到达指定时间，该缓存记录过期。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'absolute' | 否 | 否 | 策略类型。用来表示这是绝对时间过期策略。 |
| time | Date | 否 | 否 | 指定缓存过期时间。 |

## RelativeTimeExpirationPolicy

PhonePC/2in1TabletTVWearable

相对时间过期策略。经过指定的时间间隔后，该缓存记录过期。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'relative' | 否 | 否 | 策略类型。用来表示这是相对时间过期策略。 |
| time | [TimeInterval](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinterval) | 否 | 否 | 指定时间间隔。 |

## SlidingTimeExpirationPolicy

PhonePC/2in1TabletTVWearable

滑动时间过期策略。指定的时间间隔期间，若无任何访问，该缓存记录过期；若有访问，则重置过期时间。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'sliding' | 否 | 否 | 策略类型。用来表示这是滑动时间过期策略。 |
| time | [TimeInterval](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeinterval) | 否 | 否 | 指定时间间隔。 |

## TimeInterval

PhonePC/2in1TabletTVWearable

时间间隔。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| units | [TimeIntervalUnits](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timeintervalunits) | 否 | 否 | 时间间隔单位。 |
| value | number | 否 | 否 | 时间长度。 |

## TimeIntervalUnits

PhonePC/2in1TabletTVWearable

type TimeIntervalUnits = 'seconds' | 'minutes' | 'hours' | 'days'

时间间隔单位。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 类型 | 说明 |
| --- | --- |
| 'seconds' | 时间单位：秒。 |
| 'minutes' | 时间单位：分。 |
| 'hours' | 时间单位：时。 |
| 'days' | 时间单位：天。 |

## CachedResponse

PhonePC/2in1TabletTVWearable

缓存中存储的HTTP响应数据。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| timeStamp | Date | 否 | 否 | 从网络获取HTTP响应的时间。 |
| originalRequestId | string | 否 | 否 | 原始HTTP请求ID。 |
| statusCode | number | 否 | 否 | HTTP响应状态码。 |
| headers | [rcp.ResponseHeaders](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responseheaders) | 否 | 否 | HTTP响应头信息。 |
| body | ArrayBuffer | 否 | 是 | HTTP响应内容。 |
| effectiveUrl | string | 否 | 是 | 重定向后请求的有效URL。默认值为undefined。 |
| httpVersion | [rcp.HttpVersion](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpversion) | 否 | 是 | HTTP的版本。 |
| reasonPhrase | string | 否 | 是 | HTTP响应状态行的reasonPhrase，提供与数字状态代码相关的文本描述。 |
| extra | ArrayBuffer | 否 | 是 | 附加信息。该属性允许相同的URL和HTTP方法存储多条响应缓存记录。例如，开发者可以尝试放置语言类型字符串，用以匹配对应语言的响应内容。 |

## ResponseCacheKey

PhonePC/2in1TabletTVWearable

标识HTTP响应缓存记录的键。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 否 | 否 | 请求URL。 |
| method | [HttpMethod](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpmethod) | 否 | 否 | HTTP方法 |
| extra | string | 否 | 是 | 附加信息。该属性允许相同的URL和HTTP方法存储多条响应缓存记录。例如，开发者可以尝试放置语言类型字符串，用以匹配对应语言的响应内容。 |

## ResponseCacheRecord

PhonePC/2in1TabletTVWearable

缓存记录。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| expirationPolicy | [ExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#expirationpolicy) | 否 | 否 | 缓存过期策略。 |
| response | [CachedResponse](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cachedresponse) | 否 | 否 | 存储的缓存响应。 |
| key | [ResponseCacheKey](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecachekey) | 否 | 否 | 缓存响应对应的缓存键。 |

## CacheConfiguration

PhonePC/2in1TabletTVWearable

缓存配置。开发者可以通过该接口控制缓存行为，包括内存和磁盘缓存配置、缓存内存和条数上限、默认过期策略等。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| persistent | [PersistentStorageConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#persistentstorageconfiguration) | 否 | 否 | 指定持久化缓存配置。 |
| inMemory | [InMemoryCacheConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#inmemorycacheconfiguration) | 否 | 是 | 指定内存缓存配置。 |
| maxItems | number | 否 | 是 | 指定内存/持久化存储的缓存最大数量。如果设置，当缓存数量超过该阈值时，将基于LRU算法（选出最久未被使用的数据）执行淘汰策略：首先淘汰时间过期策略类型的缓存记录，其次再淘汰永不过期的缓存记录。 |
| maxSize | number | 否 | 是 | 指定内存/持久化存储所占用存储空间的上限。当缓存内存超过该阈值时，将基于LRU算法（选出最久未被使用的数据）执行淘汰策略：首先淘汰时间过期策略类型的缓存记录，其次再淘汰永不过期的缓存记录。  单位：MB。  默认值：50。 |
| defaultExpirationPolicy | [TimeLimitedExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#timelimitedexpirationpolicy) | 否 | 是 | 默认缓存过期策略。  如果设置，它将应用于每个新增的响应记录；  如果未设置，将默认设置为1小时的[SlidingTimeExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#slidingtimeexpirationpolicy)。  [set](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#set)方法配置的缓存过期策略会覆盖本接口默认缓存过期策略。 |

## PersistentStorageConfiguration

PhonePC/2in1TabletTVWearable

type PersistentStorageConfiguration = FileSystemStorageConfiguration

持久化缓存存储配置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 类型 | 说明 |
| --- | --- |
| [FileSystemStorageConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#filesystemstorageconfiguration) | 基于文件系统的缓存存储配置。 |

## FileSystemStorageConfiguration

PhonePC/2in1TabletTVWearable

基于文件系统的缓存存储配置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| kind | 'file-system' | 否 | 否 | 持久化缓存存储介质键，键值为'file-system'，表示基于文件系统介质存储。 |
| pathToFolder | string | 否 | 否 | 指定存储缓存的文件路径。可以参考[应用文件](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/app-file)。 |

## InMemoryCacheConfiguration

PhonePC/2in1TabletTVWearable

基于内存的缓存存储配置。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| maxItems | number | 否 | 是 | 指定内存缓存中的最大记录数上限。 |
| maxSize | number | 否 | 是 | 指定内存缓存所占用内存上限。若设置，则[CacheConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cacheconfiguration)中配置的maxSize对内存缓存存储不生效。  单位：MB。  默认值：10。 |

## CacheState

PhonePC/2in1TabletTVWearable

缓存状态信息。包含当前缓存条数、缓存大小和缓存命中数。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 名称 | 类型 | 只读 | 可选 | 说明 |
| --- | --- | --- | --- | --- |
| size | number | 否 | 否 | 持久化存储缓存的字节数。  单位：Byte。 |
| count | number | 否 | 否 | 当前持久化存储的缓存数量。 |
| hitCount | number | 否 | 否 | 缓存命中数。 |

## ResponseCache

PhonePC/2in1TabletTVWearable

HTTP响应缓存，为开发者提供了记录和操作HTTP缓存的能力。Remote Communication Kit不为HTTP响应缓存加密，开发者应结合自身需要选择是否使用HTTP响应缓存功能。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

### constructor

PhonePC/2in1TabletTVWearable

constructor(configuration: CacheConfiguration)

创建HTTP响应缓存实例。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| configuration | [CacheConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cacheconfiguration) | 是 | 缓存配置。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. const cache = new rcp.ResponseCache({
4. persistent: {
5. kind: 'file-system',
6. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
7. }
8. });
```

### close

PhonePC/2in1TabletTVWearable

close(): Promise<void>

关闭HTTP缓存响应实例，终止所有待处理的缓存操作。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void> | Promise对象，无返回结果。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900985](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900985-文件系统io错误) | File system IO error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. await cache.close();
11. } catch (err) {
12. console.error(`Error: error code is ${err.code}, error message is ${err.data}`);
13. }
```

### set

PhonePC/2in1TabletTVWearable

set(key: ResponseCacheKey, response: CachedResponse, expirationPolicy?: ExpirationPolicy): Promise<void>

添加或替换缓存键对应的缓存内容。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| key | [ResponseCacheKey](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecachekey) | 是 | 缓存键。 |
| response | [CachedResponse](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cachedresponse) | 是 | 需要添加或替换的HTTP缓存响应内容。 |
| expirationPolicy | [ExpirationPolicy](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#expirationpolicy) | 否 | 缓存过期策略。若传入该参数，则会覆盖[CacheConfiguration](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cacheconfiguration)中的默认缓存过期策略，即defaultExpirationPolicy。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void> | Promise对象，无返回结果。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误) | Parameter error. |
| [1007900985](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900985-文件系统io错误) | File system IO error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. const session: rcp.Session = rcp.createSession({
11. requestConfiguration: {
12. cache: cache
13. }
14. });
15. const key: rcp.ResponseCacheKey = {
16. url: 'https://www.example.com',
17. method: 'GET'
18. };
19. const response = await session.get('https://www.example.com');
20. const cachedRecord = rcp.createCachedResponse(response);
21. const policy: rcp.TimeLimitedExpirationPolicy = {
22. kind: 'relative',
23. time: {
24. units: 'seconds',
25. value: 3
26. }
27. };
28. cache.set(key, cachedRecord, policy).then(() => {
29. })
30. } catch (err) {
31. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
32. }
```

### get

PhonePC/2in1TabletTVWearable

get(key: ResponseCacheKey): Promise<ResponseCacheRecord>

获得缓存键对应的HTTP响应缓存记录。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| key | [ResponseCacheKey](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecachekey) | 是 | 缓存键。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[ResponseCacheRecord](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecacherecord)> | Promise对象，返回HTTP响应缓存记录。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误) | Parameter error. |
| [1007900985](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900985-文件系统io错误) | File system IO error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. const record = await cache.get({
11. url: 'https://www.example.com',
12. method: 'GET'
13. });
14. } catch (err) {
15. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
16. }
```

### clear

PhonePC/2in1TabletTVWearable

clear(): Promise<void>

清除HTTP响应缓存。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<void> | Promise对象，无返回结果。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900985](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900985-文件系统io错误) | File system IO error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. await cache.clear();
11. } catch (err) {
12. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
13. }
```

### getState

PhonePC/2in1TabletTVWearable

getState(): Promise<CacheState>

获取缓存状态信息。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<[CacheState](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cachestate)> | Promise对象，返回缓存状态信息。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900985](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900985-文件系统io错误) | File system IO error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. const cacheState = await cache.getState();
11. } catch (err) {
12. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
13. }
```

### remove

PhonePC/2in1TabletTVWearable

remove(key: ResponseCacheKey): Promise<boolean>

删除缓存键对应的HTTP响应缓存记录。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| key | [ResponseCacheKey](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#responsecachekey) | 是 | 缓存键。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<boolean> | Promise对象，返回true表示删除成功；返回false表示删除失败。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误) | Parameter error. |
| [1007900985](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900985-文件系统io错误) | File system IO error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. const key: rcp.ResponseCacheKey = {
11. url: 'https://www.example.com',
12. method: 'GET'
13. };
14. const result = await cache.remove(key);
15. } catch (err) {
16. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
17. }
```

### removeMultiple

PhonePC/2in1TabletTVWearable

removeMultiple(url: URLOrString, matchKind: URLMatchKind, method?: HttpMethod): Promise<boolean>

按照URL匹配类型，检索并删除一条或者多条HTTP响应缓存记录，开发者可以通过matchKind配置URL匹配类型。使用Promise异步回调。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| url | [URLOrString](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlorstring) | 是 | URL，用于与缓存键中的URL进行匹配。 |
| matchKind | [URLMatchKind](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#urlmatchkind) | 是 | URL匹配类型。 |
| method | [HttpMethod](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#httpmethod) | 否 | HTTP请求方法。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| Promise<boolean> | Promise对象，返回true表示删除成功；返回false表示删除失败。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

展开

| 错误码ID | 错误信息 |
| --- | --- |
| [1007900401](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900401-接口参数错误) | Parameter error. |
| [1007900985](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code#section1007900985-文件系统io错误) | File system IO error. |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. const result = await cache.removeMultiple('https://www.example.com', 'exact', 'GET');
11. } catch (err) {
12. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
13. }
```

## URLMatchKind

PhonePC/2in1TabletTVWearable

type URLMatchKind = 'exact' | 'as-substring'

URL匹配类型。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

展开

| 类型 | 说明 |
| --- | --- |
| 'exact' | 指定URL精准匹配。匹配的URL应等于提供的URL。 |
| 'as-substring' | 指定URL应作为子字符串进行匹配。匹配的URL应包含提供的URL。 |

## createResponse

PhonePC/2in1TabletTVWearable

createResponse(request: Request, cachedResponse: CachedResponse, currentTime: Date): Response

根据HTTP响应缓存创建HTTP响应。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| request | [Request](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#request) | 是 | 要创建响应的HTTP请求。 |
| cachedResponse | [CachedResponse](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cachedresponse) | 是 | 缓存中存储的HTTP响应缓存。 |
| currentTime | Date | 是 | 当前时间。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response) | HTTP响应。 |

**错误码：**

错误码的详细介绍请参见[API错误码](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/remote-communication-error-code)。

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir" // 请根据自身业务选择合适的路径
8. }
9. });
10. const request = new rcp.Request('https://www.example.com', 'GET');
11. const key: rcp.ResponseCacheKey = {
12. url: request.url,
13. method: request.method,
14. };
15. // 获取HTTP响应缓存结果。
16. const responseInCache = await cache.get(key);
17. if (responseInCache) {
18. // 根据HTTP响应缓存得到HTTP响应。
19. const response = rcp.createResponse(request, responseInCache.response, new Date());
20. }
21. } catch (err) {
22. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
23. }
```

## createCachedResponse

PhonePC/2in1TabletTVWearable

createCachedResponse(response: Response, timeStamp?: Date): CachedResponse

根据HTTP响应创建HTTP响应缓存。

**模型约束：** 此接口仅可在Stage模型下使用。

**系统能力：** SystemCapability.Collaboration.RemoteCommunication

**起始版本：** 6.0.0(20)

**参数：**

展开

| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| response | [Response](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#response) | 是 | HTTP响应。 |
| timeStamp | Date | 否 | 缓存的响应时间戳。默认为当前系统时间。 |

**返回值：**

展开

| 类型 | 说明 |
| --- | --- |
| [CachedResponse](/consumer/cn/doc/harmonyos-references/remote-communication-rcp#cachedresponse) | HTTP响应缓存。 |

**示例：**



```
1. import { rcp } from '@kit.RemoteCommunicationKit';

3. try {
4. const cache = new rcp.ResponseCache({
5. persistent: {
6. kind: 'file-system',
7. pathToFolder: "/path/dir", // 请根据自身业务选择合适的路径
8. }
9. });
10. const session = rcp.createSession();
11. const key: rcp.ResponseCacheKey = {
12. url: 'https://www.example.com',
13. method: 'GET'
14. };
15. // 获取HTTP响应。
16. const response = await session.get('https://www.example.com');
17. // 根据HTTP响应创建HTTP响应缓存。
18. const cachedRecord = rcp.createCachedResponse(response);
19. } catch (err) {
20. console.error(`Error: error code is ${err.code}, error data is ${err.data}`);
21. }
```