HarmonyOS rcp模块使用例子

是否有rcp模块完整的使用例子。rcp模块开发中是否支持连接池,同时对应的session是否每次请求完成后,都需要关闭

HarmonyOS
2024-12-25 17:25:32
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
FengTianYa

可以参考下面demo

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%')
  }
}
//module.json5wen文件
//需要申请如下两个权限
"requestPermissions": [
{
  "name": "ohos.permission.INTERNET"
},
{
  "name": "ohos.permission.GET_NETWORK_INFO"
}
],
//同一时间存活的Session不能超过16个,一个Session可以发起无数个请求
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.
  • 145.
  • 146.
  • 147.
  • 148.
  • 149.
  • 150.
  • 151.
  • 152.
  • 153.
  • 154.
  • 155.
  • 156.
  • 157.
  • 158.
  • 159.
  • 160.
  • 161.
  • 162.
  • 163.
  • 164.
  • 165.
  • 166.
  • 167.
  • 168.
  • 169.
  • 170.
  • 171.
  • 172.
  • 173.
  • 174.
  • 175.
  • 176.
  • 177.
  • 178.
  • 179.
  • 180.
  • 181.
  • 182.
  • 183.
  • 184.
  • 185.
  • 186.
  • 187.
  • 188.
  • 189.
  • 190.
  • 191.
  • 192.
  • 193.
  • 194.
  • 195.
  • 196.
  • 197.
  • 198.
  • 199.
  • 200.
  • 201.
  • 202.
  • 203.
  • 204.
  • 205.
  • 206.
  • 207.
  • 208.
  • 209.
  • 210.
  • 211.
  • 212.
  • 213.
  • 214.
  • 215.
  • 216.
  • 217.
  • 218.
  • 219.
  • 220.
  • 221.
  • 222.
  • 223.
  • 224.
  • 225.
  • 226.
  • 227.
  • 228.
  • 229.
  • 230.
  • 231.
  • 232.
分享
微博
QQ
微信
回复
2024-12-25 19:39:28
相关问题
使用rcp模块能力发送Get请求
2026浏览 • 1回复 待解决
rcp模块能力发起post请求
2192浏览 • 1回复 待解决
HarmonyOS rcp请求问题
821浏览 • 1回复 待解决
HarmonyOS @Expend跨模块使用问题
1031浏览 • 1回复 待解决
HarmonyOS 能否跨模块使用@Styles
752浏览 • 1回复 待解决
HarmonyOS 有没有编译openssl的例子
654浏览 • 1回复 待解决
HarmonyOS rcp能力调用demo
642浏览 • 1回复 待解决
HarmonyOS axios和rcp取舍
584浏览 • 1回复 待解决
HarmonyOS rcp取消网络请求
1003浏览 • 1回复 待解决
HarmonyOS RCP如何设置contentType
458浏览 • 1回复 待解决
HarmonyOS rcp拦截器
732浏览 • 1回复 待解决
HarmonyOS 是否有rsa加解密的例子
576浏览 • 1回复 待解决
HarmonyOS 有没有List分页加载的例子
784浏览 • 1回复 待解决