第三节 java web3j连接geth

第三节 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()); 
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

liming10101010

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值