【web3j】Web3j入门

  最近在研究以太坊智能合约,发现以太坊推出了web3.js的nodejs库,对于学Java出身的我而言非常的不习惯。

  在github中寻找到了Java版本的web3j,在这里与大家分享一下。

  web3j github地址:https://github.com/web3j/web3j

  web3j 文档地址:https://web3j.readthedocs.io/en/latest/

  

  一个简单的例子

  1、创建一个maven项目

  2、增加dependencies

  

  <dependency>
      <groupId>org.web3j</groupId>
      <artifactId>core</artifactId>
      <version>3.3.1</version>
   </dependency>

  

  3、申请测试网络

    (1)本地私链(geth)

    (2)party

    (3)infura

    第一种是本地搭建geth客户端或者搭建私链,这个优点在于全部是本地环境想干嘛干嘛,搭建私链教程地址:http://blog.csdn.net/chenyufeng1991/article/details/53471576,但是这种方式比较麻烦。

    第二种是一个以太坊的钱包,优点可以存储账号,便于管理,缺点是需要下载测试或者主网的所有block(主网的block大概40多个G)

    第三种是一个客户端,免费的节点钱包,比较方便。

    本次代码就基于infura来进行

  4、入门编码

    

 1 import org.web3j.protocol.Web3j;
 2 import org.web3j.protocol.core.methods.response.Web3ClientVersion;
 3 import org.web3j.protocol.http.HttpService;
 4 
 5 public class Web3Blog1_1 {
 6     public static void main(String[] args) throws Exception{
 7         Web3j web3 = Web3j.build(new HttpService("https://kovan.infura.io/yXDUNwlNOcx0UJCWjzNr"));
 8         Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();
 9         String clientVersion = web3ClientVersion.getWeb3ClientVersion();
10         System.out.println(clientVersion);
11     }
12 }

运行结果:

  

  

  

  

  

原文地址:https://www.cnblogs.com/hongpxiaozhu/p/8574257.html