中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
微信扫码分享
import rcp from '@hms.collaboration.rcp'; import { BusinessError } from '@kit.BasicServicesKit'; import { util } from '@kit.ArkTS'; import fs from '@ohos.file.fs'; //拦截器接收数据对象 class ResponseCache { private readonly cache: Record<string, rcp.Response> = {}; getResponse(url: string): rcp.Response { return this.cache[url]; } setResponse(url: string, response: rcp.Response): void { this.cache[url] = response; } } //自定义拦截器 class ResponseCachingInterceptor implements rcp.Interceptor { private readonly cache: ResponseCache; constructor(cache: ResponseCache) { this.cache = cache; } //拦截器获取数据方法定义 intercept(context: rcp.RequestContext, next: rcp.RequestHandler): Promise<rcp.Response> { const url = context.request.url.href; const responseFromCache = this.cache.getResponse(url); if (responseFromCache) { return Promise.resolve(responseFromCache); } const promise = next.handle(context); promise.then((resp) => { this.cache.setResponse(url, resp); }); return promise; } } @Entry @Component struct Index { @State message: string = 'Hello World'; //get请求方式获取数据 rcpGetData(){ let testUrl = 'https://www.index.com' //定义通信会话对象 const sessionConfig = rcp.createSession(); //get请求 sessionConfig.get(testUrl).then((response) => { console.log("test---------" + JSON.stringify(response)); //页面展示请求结果 AlertDialog.show( { title: 'request接口回调结果', message: '请求网站:' + testUrl + '\n\n' + 'Callback Data: ' + JSON.stringify(response), }) }).catch((err:BusinessError)=> { AlertDialog.show( { title: 'request接口回调结果', message: '请求失败,错误信息:' + err.data, }) console.error("test err:" + JSON.stringify(err)); }); } //多文件上传 multipartDataPost(){ let session = rcp.createSession(); let request = new rcp.Request('http://192.168.0.1:8080'); // 样例地址可根据实际请求替换 request.content = new rcp.MultipartForm({ file1: { contentOrPath: { content: new util.TextEncoder().encode('Text').buffer } }, file2: { contentOrPath: "/data/local/tmp/test.txt" //系统沙箱路径 }, }); const resp = session.fetch(request); console.log("resp",JSON.stringify(resp)); session.close(); } //rcp证书校验 verifyCertByGetData(){ let context: Context = getContext(this); //读取rawfile资源目录下证书内容 const keyPemConent = context.resourceManager.getRawFileContentSync('testCa.pem') let filesDir: string = context.filesDir let filePath = filesDir + "/testCer.pem"; //设备中创建写入证书文件 let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE); fs.writeSync(file.fd, keyPemConent.buffer); fs.fsyncSync(file.fd); fs.closeSync(file); const securityConfig: rcp.SecurityConfiguration = { // remoteValidation: "system", certificate: { content: keyPemConent, type: "PEM", // key: "-----BEGIN PRIVATE KEY-----\n...", // keyPassword: "your-password", }, }; // 创建使用Session集 const sessionWithSecurityConfig = rcp.createSession({ requestConfiguration: { security: securityConfig } }); sessionWithSecurityConfig.get('https://www.index.com').then((response) => { console.info('Certificate verification succeeded' ); console.info('resCode' + JSON.stringify(response.statusCode)); console.info('headers' + JSON.stringify(response.headers)); }).catch((err: BusinessError) => { console.error(`err: err code is ${err.code}, err message is ${err.message}`); }); } //DNS配置 rcpDnsTest(){ //自定义DNS服务器 const customDnsServers: rcp.DnsServers = [ //配置DNS规则 { ip: "8.8.8.8" }, { ip: "8.8.4.4", port: 53 }, ]; const sessionWithCustomDns = rcp.createSession( { requestConfiguration: { dns: { dnsRules: customDnsServers } } }); sessionWithCustomDns.get('https://www.index.com').then((response) => { console.info('Certificate verification succeeded, message is ' + JSON.stringify(response)); }).catch((err: BusinessError) => { console.error(`err: err code is ${err.code}, err message is ${err.message}`); }); } //拦截器 getDataByInterceptor(){ const cache = new ResponseCache(); const session = rcp.createSession({ interceptors: [new ResponseCachingInterceptor(cache)] }); session.get('https://www.index.com').then((response) => { console.info('get requestData :'+JSON.stringify(response.request)) console.info('get headersData :'+JSON.stringify(response.headers)) console.info('get urlData :'+JSON.stringify(response.effectiveUrl)) console.info('cache : ' + JSON.stringify(cache)) }).catch((err: BusinessError) => { console.error(`err: err code is ${err.code}, err message is ${err.message}`); }); } build() { Row() { Column() { //get请求方式获取数据 Button('getData') .onClick(()=>{ this.rcpGetData(); }) .type(ButtonType.Capsule) .margin({ top: 4 }) .backgroundColor('#ff1198ee') .width('67%') .height('4%') //多文件上传 Button('postMultiData') .onClick(()=>{ this.multipartDataPost(); }) .type(ButtonType.Capsule) .margin({ top: 4 }) .backgroundColor('#ff1198ee') .width('67%') .height('4%') //rcp证书校验 Button('verifyCertByGetData') .onClick(()=>{ this.verifyCertByGetData(); }) .type(ButtonType.Capsule) .margin({ top: 4 }) .backgroundColor('#ff1198ee') .width('67%') .height('4%') //DNS配置 Button('getDataByInterceptor') .onClick(()=>{ this.getDataByInterceptor(); }) .type(ButtonType.Capsule) .margin({ top: 4 }) .backgroundColor('#ff1198ee') .width('67%') .height('4%') } .width('100%') } .height('100%') } }