# Java×以太坊 2利用infura连接到以太坊Goerli测试网

By [先圣](https://paragraph.com/@120.show) · 2023-07-11

---

### 观前提示：

©版权所有：本教程由[先圣](https://120.show/)编写，如需转载，请标明出处。

本文受众：Web3从业人员、程序员

浏览推荐：为了最佳观感，本文地址为：[https://blog.120.show/2023/7](https://blog.120.show/2023/7)

### 正文开始：

#### 思路解析：

> 请先阅读完参考资料第二篇内容，再阅读本文。

一般来说，想要学习某个技术，正确的流程是：

先在本地安装环境、等本地测试结束后，再进行线上测试，最后进行生产部署。

以太坊的本地客户端有多种语言编写的，其中以Go语言的客户端较为出名。

当然，也有傻瓜式的软件客户端，如Ganache之类的产品。

本文，删繁就简，直接从线上的测试网环境开始，跳过了本地私有链的阶段（繁琐）。

#### 产品选择：

目前还在服役的测试网有：Goerli、Sepolia

我选择了目前更为广泛使用的Goerli，当然你也可以用Sepolia操作，他们是等同的。

在连接测试网上面，我没有选择公共的节点，而是选择可以提供私人服务的infura，当然alchemy也提供该服务。

[https://app.infura.io/](https://app.infura.io/)

> 点击上面的网站，注册账号、创建项目、你会得到一个API Key
> 
> bc809e6905c34cb1b7e3536a0934ce06
> 
> 如果你想要使用，请将下面的链接后面的key换成自己的：
> 
> [https://goerli.infura.io/v3/bc809e6905c34cb1b7e3536a0934ce06](https://goerli.infura.io/v3/bc809e6905c34cb1b7e3536a0934ce06)

#### 连接节点：

> 我默认你已经看完了我的上一篇文章，我们还是在该项目的环境下开始吧。

新建一个LinkGoerli类，当然你也可以起其他名字。

    import org.web3j.protocol.Web3j;
    import org.web3j.protocol.http.HttpService;
    public class LinkGoerli {
        public static void main(String[] args) {
            // 填写你的infura个人key
            String url = "https://goerli.infura.io/v3/bc809e6905c34cb1b7e3536a0934ce06";
            // 建立连接
            Web3j web3 = Web3j.build(new HttpService(url));
            // 你可以获取版本信息、当前区块高度、当前GAS费等信息
        }
    }
    

这样你就获得了一个web3j对象，然后就可以用它来完成你想做的事情了。

我在下面将举例说明：

    try {
                // 获取当前客户端版本
                Web3ClientVersion clientVersion = web3.web3ClientVersion().send();
                // 获取当前区块高度
                EthBlockNumber blockNumber = web3.ethBlockNumber().send();
                // 获取当前GAS费用，单位Wei
                EthGasPrice gasPrice = web3.ethGasPrice().send();
                // 打印输出
                System.out.println("客户端版本: " + clientVersion.getWeb3ClientVersion());
                System.out.println("区块高度: " + blockNumber.getBlockNumber());
                System.out.println("Gas价格: " + gasPrice.getGasPrice());
    
            } catch (IOException ex) {
                throw new RuntimeException("请求异常", ex);
            }
    

当你运行后，如果无误，控制台应该显示如下：

> 客户端版本: Geth/v1.11.6-omnibus-f83e1598/linux-amd64/go1.20.3 区块高度: 9328235 Gas价格: 349196119

#### 查询余额：

新建一个GetEtherBalance类，代码如下：

    import java.math.BigDecimal;
    import java.util.concurrent.ExecutionException;
    import org.web3j.protocol.Web3j;
    import org.web3j.protocol.core.DefaultBlockParameterName;
    import org.web3j.protocol.core.methods.response.EthGetBalance;
    import org.web3j.protocol.http.HttpService;
    import org.web3j.utils.Convert;
    
    public class GetEtherBalance {
        public static void main(String[] args) throws ExecutionException, InterruptedException {
            // 填写你的infura个人key
            String url = "https://goerli.infura.io/v3/bc809e6905c34cb1b7e3536a0934ce06";
            // 建立连接
            Web3j web3 = Web3j.build(new HttpService(url));
            // 以太坊地址
            String address = "0x17a04150123b23cfb2c21b599e68d2a0d35dbf6b";
            // 获取余额 Wei
            EthGetBalance balance = web3.ethGetBalance(address, DefaultBlockParameterName.LATEST).sendAsync().get();
            // 转换余额单位 Eth
            BigDecimal etherBalance = Convert.fromWei(balance.getBalance().toString(), Convert.Unit.ETHER);
            // 输出余额
            System.out.println("余额：" + etherBalance);
        }
    }
    

查询余额只需要地址即可，不需要私钥，但是转账需要（下一篇内容）。

正常情况下，刚创建的钱包是没有余额的，所以余额为0是对的。

你可以从其他地方获取一点GETH。比如水龙头，或者其他的钱包里面转账一点。

如果只是学习，其实我更加推荐使用Sepolia，毕竟Goerli的水实在太难领取了，但是买的话还是非常简单的。

我开始认同那句话了，与其花上几个小时来寻找水龙头，还不如花一杯咖啡/奶茶的价格买上足够测试的代币。

### 参考资料：

[https://chat.openai.com/](https://chat.openai.com/)

[https://blog.120.show/2023/5](https://blog.120.show/2023/5)

[https://kauri.io/#communities/Java%20Ethereum/connecting-to-an-ethereum-client-with-java-eclips/](https://kauri.io/#communities/Java%20Ethereum/connecting-to-an-ethereum-client-with-java-eclips/)

---

*Originally published on [先圣](https://paragraph.com/@120.show/java-2-infura-goerli)*
