区块链学习之Web3j入门

1、开启以太坊节点服务

在很多其他的博客上,我看的都是自己搭建的ganache-cli的以太坊仿真器节点,通过命令生成自己的链和账户,我由于懒得搞内网自己搞链,所以我直接用的以太坊的测试节点来做的

测试节点地址:https://docs.infura.io/infura/networks/ethereum/json-rpc-methods/eth_sendtransaction

先注册=》创建项目=〉进入自己的项目

选择项目属性

复制自己的测试网节点地址(下拉到自己的测试网地址)

出现以上信息,测试节点就搭建完了

2、用maven中导入相关依赖

<!--引入单元测试-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
 <!--导入web3j核心jar包-->
      <dependency>
        <groupId>org.web3j</groupId>
        <artifactId>core</artifactId>
        <version>4.3.0</version>
      </dependency>
      <!--引入日志组件-->
    <dependency>
      <groupId>ch.qos.logback</groupId>
      <artifactId>logback-core</artifactId>
      <version>1.1.7</version>
    </dependency>
    <dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>1.1.7</version>
    </dependency>

3、代码编写

接口 Web3j 声明了以太坊 JSON RPC 相关的全部接口,该接口提供了静态方法 build()来返回一个该接口实现类JsonRpc2_0Web3j 的实例对象:

    public static void main(String[] args) throws IOException {
        //创建一个 Web3j 实例对象,该对象将后续的 RPC 调用通过 HTTP 发送到(tie测试链上)的节点,这个节点也可以变化,比如:https://ropsten.infura.io/v3/project id
        Web3j web3j = Web3j.build(new HttpService("https://rpc.testnet.tie.tech"));
        //构造请求对象
        Request<?, Web3ClientVersion> request = web3j.web3ClientVersion();
        //发送请求对象并获取响应对象
        Web3ClientVersion response = request.send();
        //获取版本信息
        String version = response.getWeb3ClientVersion();
        //输出版本信息
        System.out.println("Client Version:"+version);
    }

结论:

posted @ 2022-06-17 15:39  小学程序员  阅读(302)  评论(0编辑  收藏  举报