"使用 ETH Java-SDK 获取区块高度和区块哈希,你可以使用以下代码:\n\njava\nimport org.web3j.protocol.Web3j;\nimport org.web3j.protocol.core.DefaultBlockParameter;\nimport org.web3j.protocol.core.DefaultBlockParameterName;\nimport org.web3j.protocol.core.methods.request.EthBlock;\nimport org.web3j.protocol.core.methods.response.EthBlock.Block;\nimport org.web3j.protocol.http.HttpService;\nimport java.io.IOException;\nimport java.math.BigInteger;\n\npublic class EthBlockInfo {\n public static void main(String[] args) {\n // 创建web3j对象,并设置以太坊节点的URL\n Web3j web3j = Web3j.build(new HttpService(\"https://mainnet.infura.io/v3/your_infura_project_id\"));\n\n try {\n // 获取当前最新的区块高度\n BigInteger blockHeight = web3j.ethBlockNumber().send().getBlockNumber();\n System.out.println(\"当前区块高度:\" + blockHeight);\n\n // 获取指定区块的区块信息\n DefaultBlockParameter defaultBlockParameter = DefaultBlockParameter.valueOf(blockHeight);\n EthBlock ethBlock = web3j.ethGetBlockByNumber(defaultBlockParameter, true).send();\n Block block = ethBlock.getBlock();\n String blockHash = block.getHash();\n System.out.println(\"当前区块Hash:\" + blockHash);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n\n\n上述代码首先创建了一个web3j对象,然后使用ethBlockNumber()方法获取当前最新的区块高度,并使用ethGetBlockByNumber()方法获取指定区块的区块信息。最后,通过调用getHash()方法获取区块的Hash值。\n\n这段代码使用了web3j库来与以太坊网络进行交互。需要注意的是,你需要将https://mainnet.infura.io/v3/your_infura_project_id替换为你自己的Infura项目ID。\n\n在运行代码时,你将会得到当前最新的区块高度和指定区块的区块Hash。\n

ETH Java-SDK 获取区块高度和区块哈希:代码示例及解析

原文地址: https://www.cveoy.top/t/topic/pE0M 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录