第三节 java web3j连接geth
引入jar包
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>5.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.web3j/geth -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>geth</artifactId>
<version>5.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.web3j/abi -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>abi</artifactId>
<version>5.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.web3j/utils -->
<dependency>
<groupId>org.web3j</groupId>
<artifactId>utils</artifactId>
<version>5.0.0</version>
</dependency>
创建web3j的http连接,代码如下:
static String url = "http://127.0.0.1:8545";
public static HttpService getService() {
OkHttpClient oc = new OkHttpClient.Builder()
.connectTimeout(60 * 5, TimeUnit.SECONDS)
.readTimeout(60 * 5, TimeUnit.SECONDS)
.writeTimeout(60 * 5, TimeUnit.SECONDS)
.build();
HttpService httpService = new HttpService(url, oc);
return httpService;
}
public static Web3j getConnection(HttpService httpService) {
Web3j web3 = Web3j.build(httpService);
return web3;
}
使用:
static HttpService httpService = Web3jService.getService();
static Web3j web3j = Web3jService.getConnection(httpService);
此时的web3j就可以进行geth的操作了。
比如获取geth里面的账号:
List<String> accounts = web3j.ethAccounts().send().getAccounts();
比如是否挖矿:
boolean mining = web3j.ethMining().send().isMining();
比如获取最新的编号:
web3j.ethBlockNumber().send().getBlockNumber();
获取chainIdID:
BigInteger chainId = web3j.ethChainId().send().getChainId();
更多的方法大家可以根据API进行测试,其中send()方法是同步,以上所都可以进行异步获取,比如:
web3j.ethAccounts().sendAsync().whenComplete((ethAccounts, throwable) -> {
System.out.println(ethAccounts.getAccounts().size());
});