区块链学习之Web3j入门(一)

1.开启ganache-cli服务

ganache-cli 是以太坊节点仿真器软件 ganache 的命令行版本,可以方便开发者快速进行以太坊DApp的开发与测试,开启服务后如下图所示(初始有十个账户信息):
区块链学习之Web3j入门(一)_第1张图片ganache-cli运行在8545端口监听http请求,我们将使用web3j将JSON RPC 调用请求使用http协议发送到节点的8545端口。

2.用maven中导入相关依赖

<dependencies>

    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
 
      <dependency>
        <groupId>org.web3jgroupId>
        <artifactId>coreartifactId>
        <version>4.3.0version>
      dependency>
      
    <dependency>
      <groupId>ch.qos.logbackgroupId>
      <artifactId>logback-coreartifactId>
      <version>1.1.7version>
    dependency>
    <dependency>
    <groupId>ch.qos.logbackgroupId>
    <artifactId>logback-classicartifactId>
    <version>1.1.7version>
    dependency>
  dependencies>

3.主函数

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

org.example.App

package org.example;

import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.Request;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;

import java.io.IOException;

/**
* Hello Web3j!
*
*/
public class App 
{
     
  public static void main( String[] args ) throws IOException {
     
      Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));//创建一个 Web3j 实例对象,该对象将后续的 RPC 调用通过 HTTP 发送到本机运
行的节点
      Request<?, Web3ClientVersion> request = web3j.web3ClientVersion(); //构造请求对象
      Web3ClientVersion response = request.send();//发送请求对象并获取响应对象
      String version = response.getWeb3ClientVersion();//获取版本信息
      System.out.println("Client Version:"+version);//输出版本信息
  }
}
String clientVersion = web3j.web3ClientVersion().send().getWeb3ClientVersion();//链式编程实现

4.运行结果

控制台上打印出了Client Version:
运行结果

你可能感兴趣的:(区块链,区块链,java,接口,编程语言)