准备工作

将最新版本的web3j加入到项目配置中

Maven

Java 8:

org.web3j

core

2.2.1

Android:

org.web3j

core-android

2.1.0

Gradle

Java 8:

compile ('org.web3j:core:2.2.1')

Android:

compile ('org.web3j:core-android:2.1.0')

启动客户端

如果已经启动客户端,则不需要再次启动。

使用geth脚步进行启动

$ geth --fast --cache=512 --rpcapi personal,db,eth,net,web3 --rpc --testnet

使用Parity启动

$ parity --chain testnet

使用Infura提供的免费客户端启动

Web3j web3 = Web3j.build(new InfuraHttpService("https://morden.infura.io/your-token"));

如果需要详细了解Infura的启动方式,可以阅读Using Infura with web3j。

请求发送

使用Future发送异步请求

Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/

Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().sendAsync().get();

String clientVersion = web3ClientVersion.getWeb3ClientVersion();

使用RxJava的Observable

Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/

web3.web3ClientVersion().observable().subscribe(x -> {

String clientVersion = x.getWeb3ClientVersion();

...

});

发送同步请求

Web3j web3 = Web3j.build(new HttpService()); // defaults to http://localhost:8545/

Web3ClientVersion web3ClientVersion = web3.web3ClientVersion().send();

String clientVersion = web3ClientVersion.getWeb3ClientVersion();

Android使用方式

Web3j web3 = Web3jFactory.build(new HttpService()); // defaults to http://localhost:8545/ ...

IPC

web3j同样支持快速的IPC进程间通信,可使用文件套接字在同一个host上运行多个客户端作为web3j。创建服务时使用相关IpcService的实现,而不是使用HttpService。

// OS X/Linux/Unix:

Web3j web3 = Web3j.build(new UnixIpcService("/path/to/socketfile"));

...

// Windows

Web3j web3 = Web3j.build(new WindowsIpcService("/path/to/namedpipefile"));

...

注意:IPC通信在web3j-android中时不可用的。

Filters

web3j的响应式函数能够很简单的使观察者通过事件去通知订阅者,并记录在区块链中。

接受所有新的区块并把它们添加到区块链中。

Subscription subscription = web3j.blockObservable(false).subscribe(block -> {

...

});

接受所有新的交易并把它们添加到区块链中。

Subscription subscription = web3j.transactionObservable().subscribe(tx -> {

...

});

接受所有已经提交到网络中的等待处理的交易。(它们必须分在同一个区块中。)

Subscription subscription = web3j.pendingTransactionObservable().subscribe(tx -> {

...

});

如果你重置了所有的区块到最新的,那么将被随后新建的区块通知。

Subscription subscription = catchUpToLatestAndSubscribeToNewBlocksObservable(

, )

.subscribe(block -> {

...

});

一部分其他的交易和区块可重置观察,详细描述可见 Filters and Events。

主题过滤同样被支持:

EthFilter filter = new EthFilter(DefaultBlockParameterName.EARLIEST,

DefaultBlockParameterName.LATEST, )

.addSingleTopic(...)|.addOptionalTopics(..., ...)|...;

web3j.ethLogObservable(filter).subscribe(log -> {

...

});

当订阅不在需要时,订阅应该被取消。

subscription.unsubscribe();

注意:filters在Infura中不支持。

需要了解更多有关过滤器和事件的信息可以查看Filters and Events和Web3jRx 的接口

Transactions

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐