
通过Web3j接口连接以太坊[Parity/Maven/Eclipse]
Web3j接口连接以太坊全部过程详解
目录
一、Java开发环境
1.JDK下载
参考我上篇文章JDK和eclipse的环境配置,全部搭建好以后进入下面步骤。
二、Maven项目创建
1.Maven项目创建
1)启动Eclipse,点击File > New > Project > Maven > Maven Project > Next
2)选中Create a simple project (跳过 archetype selection)然后点击 Next
3)输入项目的Group ID 和Artifact ID,然后点击Finish。
Group Id: io.kauri.tutorials.java-ethereum
Artifact Id: java-ethereum
4)完成后如下界面
5)Eclipse和Maven还要使用Java所匹配的版本。我这里是java8,需编辑pom.xml文件并在</project>
之前添加,然后保存:
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
6)右键点击项目名并选择 Maven > Update Project,在弹出的对话框中点击OK。看到项目浏览器中的JER系统库从JavaSE-1.5变成了JavaSE-1.8:
三、将web3j库加入项目
1)将web3j的最新版本通过maven导入项目,在Eclipse中编辑文件pom.xml并在</project>
之前添加以下内容:
<dependencies>
<dependency>
<groupId>org.web3j</groupId>
<artifactId>core</artifactId>
<version>4.3.0</version>
</dependency>
</dependencies>
保存上述文件后就会自动导入声明的依赖包,之后在包浏览器中会看到一个Maven依赖文件夹其中包含了web3j等JAR包。
2)创建Main类:右键点击项目并选择New > Class,输入包名 io.kauri.tutorials.java_ethereum、类名Main,并选中public static void main(String[] args),最后点finish:
3)使用web3j连接以太坊节点,下面是完整的以太坊区块链Java访问代码
//Main.java
package io.kauri.tutorials.java_ethereum;
import java.io.IOException;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;
import org.web3j.protocol.http.HttpService;
//以上是代码需要的包
public class Main {
public static void main(String[] args) {
System.out.println("Connecting to Ethereum ...");
Web3j web3 = Web3j.build(new HttpService("http://localhost:8540"));
//要连接以太坊节点,Web3j需要JSON-RPC API访问端结点,http://localhost:8540这个根据自己以太坊接口端输入,8540是我搭建parit的接口端
System.out.println("Successfuly connected to Ethereum");
try {
// web3_clientVersion returns the current client version.
Web3ClientVersion clientVersion = web3.web3ClientVersion().send();
// eth_blockNumber returns the number of most recent block.
EthBlockNumber blockNumber = web3.ethBlockNumber().send();
// eth_gasPrice, returns the current price per gas in wei.
EthGasPrice gasPrice = web3.ethGasPrice().send();
// Print result
System.out.println("Client version: " + clientVersion.getWeb3ClientVersion());
System.out.println("Block number: " + blockNumber.getBlockNumber());
System.out.println("Gas price: " + gasPrice.getGasPrice());
} catch (IOException ex) {
throw new RuntimeException("Error whilst sending json-rpc requests", ex);
//JSON-RPC请求的序列化可能会出现IOException异常,因此需要处理一下。
}
}
}
4)本地运行Geth、Parity、Pantheon或Ganache-cli,并让节点保持连通状态,详情文档见文档:Linux下parity联盟链的实现_boy918.的博客-CSDN博客
5)右键点击文件Main.java,并选择 Run As > Java Application运行Java程序,初次可能会遇到这个错误,需要在pom.xml添加依赖
6)在pom.xml添加依赖并保存,重新运行项目,看到控制台显示如下内容
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
<scope>compile</scope>
</dependency>
以上为Web3j接口连接以太坊全部过程。如有疑点,请私信我。
更多推荐
所有评论(0)