开发准备,申请获取网络权限:ohos.permission.INTERNET。
场景一:简单字符串表单数据传输
let paramsObject = new url.URLParams();
paramsObject.append('fod', '3'); // 开发者自行设置参数
paramsObject.append('fed', '4'); // 开发者自行设置参数 let urlWithParam = url.URL.parseURL('/get?' + paramsObject.toString(), baseUrl); let session = rcp.createSession();
session.get(urlWithParam).then((response) => {
console.info(`urlWithParamGetData Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: err code is ${err.code}, err message is ${JSON.stringify(err)}`);
}); 运行日志如下:

const simpleForm = new rcp.Form({
'key1': 'value1',
'key2': ['valueList0', 'valueList1'],
}); // 开发者自行设置参数 simpleForm.keys = ['key2', 'key1']; // 开发者自行设置参数顺序
const session = rcp.createSession();
session.post('xxx.xxx.xxx', simpleForm).then((response) => { // 开发者自行设置请求地址
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: err code is ${err.code}, err message is ${JSON.stringify(err)}`);
}); 运行日志如下,如果用户不在请求头设置数据大小,rcp模块会自动计算:

场景二:复杂混合表单数据传输
let sandBoxFileName = await copyFileToSandBox(sandboxDir);
let multiFormFieldValue = this.buildMultipartFormFieldValue(remoteFileName, sandBoxFileName, 'image/jpeg');
let multiForm = new rcp.MultipartForm({
'key1': 'value1',
'key2': multiFormFieldValue,
'key3': multiFormFieldValue
}); // 开发者自行设置参数 multiForm.keys = ['key3', 'key1', 'key2']; // 开发者自行设置参数顺序
multiForm.boundary = '--MULTIPARTFORM BEGIN AND END BOUNDARY'; // 开发者自行设置分隔符
运行日志如下:

完整示例代码如下:
import { ItemRestriction, SegmentButton, SegmentButtonOptions, SegmentButtonTextItem } from '@kit.ArkUI';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import fileIo from '@ohos.file.fs';
import { rcp } from '@kit.RemoteCommunicationKit';
import { url } from '@kit.ArkTS';
async function getFileAssetsFromType(): Promise<string> {
let photoPicker = new photoAccessHelper.PhotoViewPicker();
const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions(); // 创建图片-音频类型文件-预览的图库选项实例
// 选择媒体文件类型和选择媒体文件的最大数目
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // 选择媒体文件类型为Image
photoSelectOptions.maxSelectNumber = 1; // 选择媒体文件的最大数目
photoSelectOptions.isEditSupported = true;
photoSelectOptions.isOriginalSupported = true;
let photoSelectResult: photoAccessHelper.PhotoSelectResult = await photoPicker.select(photoSelectOptions);
let uris: Array<string> = photoSelectResult.photoUris;
if (uris.length === 0) {
console.info('getFileAssetsFromType 没有图片选中');
}
return uris[0];
}
async function copyFileToSandBox(sandboxDir: string): Promise<string> {
let uri: string = await getFileAssetsFromType();
if (uri.length === 0) {
console.info('copyFileToSandBox 没有图片选中');
return '';
}
const fileName = uri.split('/').pop() || 'default.jpg'; // 提取文件名
console.info('沙箱路径:' + sandboxDir);
console.info('选择图片文件名称:' + fileName);
console.info('uris文件路径:' + uri);
let sandboxFilename = `${sandboxDir}/${fileName}`; // 也可以直接使用沙箱路径字符串如:/data/storage/el2/base/files
console.info('沙箱路径图片文件名:' + sandboxFilename);
const srcFile = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY); // 复制文件到沙箱
try {
fileIo.copyFileSync(srcFile.fd, sandboxFilename);
} catch (error) {
console.error('copy file error');
}
fileIo.closeSync(srcFile);
return sandboxFilename;
}
@Component
struct SimpleFormData {
urlWithParamMsg: string = 'url携带参数';
formDataMsg: string = 'requestContent传输表单';
urlWithParamGetData() {
let baseUrl: string = 'xxx.xxx.xxx'; // 开发者自行设置请求地址
let paramsObject = new url.URLParams();
paramsObject.append('fod', '3'); // 开发者自行设置参数
paramsObject.append('fed', '4'); // 开发者自行设置参数
console.info('param: ' + paramsObject.toString());
let urlWithParam = url.URL.parseURL('/get?' + paramsObject.toString(), baseUrl);
console.info('url: ' + urlWithParam.toString());
let session = rcp.createSession();
session.get(urlWithParam).then((response) => {
console.info(`urlWithParamGetData Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: err code is ${err.code}, err message is ${JSON.stringify(err)}`);
});
}
formDataTrans() {
const simpleForm = new rcp.Form({
'key1': 'value1',
'key2': ['valueList0', 'valueList1'],
}); // 开发者自行设置参数
simpleForm.keys = ['key2', 'key1']; // 开发者自行设置参数顺序
const session = rcp.createSession();
session.post('xxx.xxx.xxx', simpleForm).then((response) => { // 开发者自行设置请求地址
console.info(`Succeeded in getting the response ${response}`);
}).catch((err: BusinessError) => {
console.error(`err: err code is ${err.code}, err message is ${JSON.stringify(err)}`);
});
}
build() {
Column() {
Button(this.urlWithParamMsg)
.onClick(() => {
this.urlWithParamGetData();
})
.margin(16)
.width('100%');
Button(this.formDataMsg)
.onClick(() => {
this.formDataTrans();
})
.margin(16)
.width('100%');
}
.width('100%')
.height('100%');
}
}
@Component
struct MultiPartFormData {
hybridDataMsg: string = '多部分表单传输混合数据';
sandboxDir: string = '';
aboutToAppear(): void {
this.sandboxDir = this.getUIContext().getHostContext()!.filesDir;
}
buildMultipartFormFieldValue(fileName: string | undefined,
pathOrContent: rcp.Path | rcp.FileContent | rcp.GetDataCallback,
contentType: string | undefined): rcp.MultipartFormFieldValue {
let result: rcp.MultipartFormFieldValue = {
remoteFileName: fileName,
contentType: contentType,
contentOrPath: pathOrContent
};
return result;
}
uploadMultiPartFormFileForCommon(multiForm: rcp.MultipartForm) {
let req = new rcp.Request('xxx.xxx.xxx'); // 需开发者自行配置请求地址
req.content = multiForm;
req.method = 'POST';
try {
const session = rcp.createSession();
session.fetch(req).then((resp: rcp.Response) => {
console.info(`Response succeeded: ${JSON.stringify(resp)}`);
session.close();
}).catch((err: BusinessError) => {
// 请求错误处理。
console.error(`Response err: Code is ${JSON.stringify(err.code)}, message is ${JSON.stringify(err)}`);
session.close();
});
} catch (err) {
// 创建会话错误处理。
console.error(`createSession err: Code is ${JSON.stringify(err.code)}, message is ${JSON.stringify(err)}`);
}
}
async uploadFormSandBoxFileWithParam(sandboxDir: string) {
let remoteFileName: string = 'test.jpg';
let sandBoxFileName = await copyFileToSandBox(sandboxDir);
let multiFormFieldValue = this.buildMultipartFormFieldValue(remoteFileName, sandBoxFileName, 'image/jpeg');
let multiForm = new rcp.MultipartForm({
'key1': 'value1',
'key2': multiFormFieldValue,
'key3': multiFormFieldValue
}); // 开发者自行设置参数
multiForm.keys = ['key3', 'key1', 'key2']; // 开发者自行设置参数顺序
multiForm.boundary = '--MULTIPARTFORM BEGIN AND END BOUNDARY'; // 开发者自行设置分隔符
this.uploadMultiPartFormFileForCommon(multiForm);
}
build() {
Column() {
Button(this.hybridDataMsg)
.onClick(() => {
this.uploadFormSandBoxFileWithParam(this.sandboxDir);
})
.margin(16)
.width('100%');
}
.width('100%')
.height('100%');
}
}
@Entry
@Component
struct FormDataTransfer {
fontColor: string = '#182431';
selectedFontColor: string = '#0A59F7';
@State currentIndex: number = 0;
@State selectedIndex: number = 0;
@State tabSelectedIndexes: number[] = [0]; // SegmentButton默认选项
@State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
buttons: [{ text: '简单表单传输' }, { text: '多部分表单传输' },] as ItemRestriction<SegmentButtonTextItem>,
backgroundColor: '#0d000000',
selectedBackgroundColor: $r('sys.color.white'),
fontWeight: 400,
selectedFontWeight: 500,
textPadding: 6
});
private controller: TabsController = new TabsController();
@Builder
tabBuilder(index: number, name: string) {
Column() {
Text(name)
.fontColor(this.selectedIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(16)
.fontWeight(this.selectedIndex === index ? 500 : 400)
.lineHeight(22)
.margin({ top: 17, bottom: 7 });
Divider()
.strokeWidth(2)
.color('#007DFF')
.opacity(this.selectedIndex === index ? 1 : 0);
}.width('100%');
}
build() {
Column() {
SegmentButton({
options: this.tabOptions,
selectedIndexes: $tabSelectedIndexes,
onItemClicked: (index) => {
this.getUIContext().animateTo({ duration: 400 }, () => {
this.currentIndex = index;
this.controller.changeIndex(index);
});
}
})
.borderRadius(20)
.margin({
bottom: 16
})
.width('100%')
.height(40);
Tabs({ barPosition: BarPosition.Start, index: this.currentIndex, controller: this.controller }) {
TabContent() {
SimpleFormData();
}.tabBar(this.tabBuilder(0, '简单表单传输'));
TabContent() {
MultiPartFormData();
}.tabBar(this.tabBuilder(1, '多部分表单传输'));
}
.vertical(false)
.barMode(BarMode.Fixed)
.barWidth(360)
.barHeight(0)
.onChange((index: number) => {
// currentIndex控制TabContent显示页签
this.currentIndex = index;
this.selectedIndex = index;
})
.onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
if (index === targetIndex) {
return;
}
console.info(`event currentOffset ${event.currentOffset}`);
// selectedIndex控制自定义TabBar内Image和Text颜色切换
this.selectedIndex = targetIndex;
})
.width('100%')
.height('100%');
}
.width('100%')
.padding({
left: 16,
right: 16,
top: 12
});
}
}