HarmonyOS rcp模块使用例子

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

HarmonyOS
1天前
浏览
收藏 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可以发起无数个请求
分享
微博
QQ
微信
回复
1天前
相关问题
使用rcp模块能力发送Get请求
1099浏览 • 1回复 待解决
rcp模块能力发起post请求
1285浏览 • 1回复 待解决
HarmonyOS rcp取消网络请求
69浏览 • 1回复 待解决
HarmonyOS rcp能力调用demo
29浏览 • 1回复 待解决
HarmonyOS @Expend跨模块使用问题
410浏览 • 1回复 待解决
HarmonyOS 能否跨模块使用@Styles
339浏览 • 1回复 待解决
HarmonyOS rcp请求问题
63浏览 • 1回复 待解决
HarmonyOS http/rcp有cookieManager吗
44浏览 • 1回复 待解决
HarmonyOS rcp网络请求报错1007900994
38浏览 • 1回复 待解决
HarmonyOS 是否有rsa加解密的例子
45浏览 • 1回复 待解决
HarmonyOS rcp拦截器
65浏览 • 1回复 待解决
HarmonyOS rcp通用请求的Promise封装
63浏览 • 1回复 待解决
HarmonyOS rcp创建connection连接数
36浏览 • 1回复 待解决
HarmonyOS 音频重新编码的完整例子
37浏览 • 1回复 待解决
模块应用使用startAbility报错
1856浏览 • 1回复 待解决
HarmonyOS rcp支持cookie管理吗?
222浏览 • 1回复 待解决