HarmonyOS 鸿蒙Next中rcp能力调用demo

HarmonyOS 鸿蒙Next中rcp能力调用demo 有没有rcp能力调用demo

3 回复

可以参考此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.baidu.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 = {
      certificate: {
        content: keyPemConent,
        type: "PEM",
      },
    };
    // 创建使用Session集
    const sessionWithSecurityConfig = rcp.createSession({ requestConfiguration: { security: securityConfig } });
    sessionWithSecurityConfig.get("https://www.baidu.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.baidu.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.baidu.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%')
  }
}

更多关于HarmonyOS 鸿蒙Next中rcp能力调用demo的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙Next)中,RCP(Remote Call Procedure)能力调用允许开发者在不同设备之间进行远程调用。以下是一个简单的RCP能力调用Demo示例:

  1. 定义Ability:首先,定义一个Ability,该Ability将提供远程调用的接口。
import Ability from '@ohos.application.Ability';
import rpc from '@ohos.rpc';

export default class MyAbility extends Ability {
    onConnect(want) {
        return new MyStub('rpcToken');
    }
}

class MyStub extends rpc.RemoteObject {
    constructor(descriptor) {
        super(descriptor);
    }

    onRemoteRequest(code, data, reply, option) {
        if (code === 1) {
            let param = data.readString();
            let result = this.handleRequest(param);
            reply.writeString(result);
        }
        return true;
    }

    handleRequest(param) {
        return `Handled: ${param}`;
    }
}
  1. 调用远程Ability:在另一个设备或Ability中,调用远程Ability。
import Ability from '@ohos.application.Ability';
import rpc from '@ohos.rpc';

export default class CallerAbility extends Ability {
    async onStart(want) {
        let options = new rpc.MessageOption();
        let data = rpc.MessageParcel.create();
        let reply = rpc.MessageParcel.create();
        data.writeString('Hello, RPC');
        let remoteObject = await this.connectAbility(want);
        remoteObject.sendRequest(1, data, reply, options);
        let result = reply.readString();
        console.log(`Result: ${result}`);
    }
}
  1. 配置文件:在config.json中配置Ability。
{
    "app": {
        "bundleName": "com.example.myapp",
        "version": {
            "code": 1,
            "name": "1.0"
        }
    },
    "deviceConfig": {},
    "module": {
        "package": "com.example.myapp",
        "name": ".MyAbility",
        "abilities": [
            {
                "name": "MyAbility",
                "visible": true,
                "skills": [
                    {
                        "entities": ["entity.system.home"],
                        "actions": ["action.system.home"]
                    }
                ]
            },
            {
                "name": "CallerAbility",
                "visible": true,
                "skills": [
                    {
                        "entities": ["entity.system.home"],
                        "actions": ["action.system.home"]
                    }
                ]
            }
        ]
    }
}

此Demo展示了如何在HarmonyOS中通过RPC进行远程调用。

在HarmonyOS(鸿蒙)Next中,RPC(Remote Procedure Call,远程过程调用)能力允许设备间进行跨进程通信。以下是一个简单的RPC调用Demo:

  1. 定义接口:首先在IDL文件中定义RPC接口。
interface IMyService {
    int add(int a, int b);
}
  1. 实现服务端:实现IMyService接口。
public class MyService extends IMyService.Stub {
    @Override
    public int add(int a, int b) {
        return a + b;
    }
}
  1. 注册服务:在服务端注册RPC服务。
MyService myService = new MyService();
ServiceManager.addService("my_service", myService);
  1. 客户端调用:客户端通过ServiceManager获取服务并调用。
IMyService myService = IMyService.Stub.asInterface(ServiceManager.getService("my_service"));
int result = myService.add(3, 4);

通过以上步骤,你可以在鸿蒙Next中实现基本的RPC调用。

回到顶部