Ethereum Web3j/Maven/Eclipse development environment setup tutorial

In this tutorial, we will learn how to create a Java Ethereum project managed by Maven in Eclipse, use the web3j library to connect to the Ethereum node, execute JSON-RPC API calls and display the results.

Use their own familiar language learning Ethernet Square DApp development: the Java | Php | Python | .Net / C # | golang | Node.JS | Flutter / Dart

web3j is a lightweight, modular development library, which implements all the functions required to interact with Ethereum, including JSON-RPC API client, wallet account management, Java smart contract wrapper, ENS, ERC20, ERC721 and other features support and so on.

1. Prepare the Java Ethereum development environment

You need to install Java 8 first . Use the following command to verify the installation of java:

$ java -version
java version "1.8.0_201"

Secondly, we need a package manager, such as Maven or Gradle . In this tutorial, we use Maven to manage dependencies. If you want to use Gradle, you can check this tutorial: Use Gradle to develop web3j Ethereum applications in Eclipse .

Finally, we need an integrated development environment, such as Eclipse used in this tutorial .

2. Create a new Maven project

In this environment, the task we want to accomplish is to create a new Maven project in Eclipse and name it java_ethereum:

Insert picture description here

  • After starting Eclipse, go to the File> New> Project> Maven> Maven Project menu.
  • Check Create a simple project (skip archetype selection) and click Next>
  • Enter the Group ID and Artifact ID of the project, and then click Finish.
    • Group Id: io.kauri.tutorials.java-ethereum
    • Artifact Id: java-ethereum

The following should be displayed in the project browser:

Insert picture description here
Finally, we also need to tell Eclipse and Maven to use Java 8. Edit the pom.xml file and </project>before:

<properties>
  <maven.compiler.target>1.8</maven.compiler.target>
  <maven.compiler.source>1.8</maven.compiler.source>
</properties>

Right-click the project name in the project browser and select Maven> Update Project, and click OK in the pop-up dialog box. You should see the JER system library in the project browser changed from JavaSE-1.5 to JavaSE-1.8:

Insert picture description here

3. Add the web3j library to the project

In this step, we import the latest version of web3j into the project through maven.

Edit the file pom.xml in Eclipse and </project>add the following content before it:

<dependencies>
  <dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>4.3.0</version>
  </dependency>
</dependencies>

The complete pom.xml file can be found here .

After saving the above file, the declared dependency package will be imported. In the package browser, you will see a Maven dependency folder that contains JAR packages such as web3j.

4. Create the Main class

Now that we have all the dependencies needed to use Web3j, we can start writing Ethereum Java programs.

Right-click the project and select New> Class to create a Java class Main.java. Enter the package name
io.kauri.tutorials.java_ethereum and the class name Main and select public static void main(String[] args):

Insert picture description here

Click Finish to generate the file.

//Main.java
package io.kauri.tutorials.java_ethereum;

public class Main {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
  }
}

5. Use web3j to connect to Ethereum nodes

We have created the project, imported the Web3j library and started to prepare the implementation code. Now we can connect to an Ethereum node and use Web3j's JSON-RPC API abstraction to perform some Ethereum operations.

First introduce the packages needed by the code, or allow your IDE to automatically import:

import java.io.IOException;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.protocol.core.methods.response.EthBlockNumber;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import org.web3j.protocol.core.methods.response.Web3ClientVersion;

To connect to the Ethereum node, Web3j needs the JSON-RPC API access node:

Web3j web3 = Web3j.build(new HttpService("<NODE ENDPOINT>"));

If you are running Getth, Parity, Pantheon or Ganache-cli locally, then the default JSON-RPC API end node of your node is http://localhost:8545:

Web3j web3 = Web3j.build(new HttpService("http://localhost:8545"));

If you run the graphical Ganache application on your own machine, the default end node of your JSON-RPC API is http://localhost:7545:

Web3j web3 = Web3j.build(new HttpService("http://localhost:7545"));

Note: As a test chain, not all JSON-RPC APIs of Ganache are supported, such as net_peercount.

If you are using Infura , the JSON-RPC API end of the node is https://<network>.infura.io/v3/<project key>:

Web3j web3 = Web3j.build(new HttpService("https://mainnet.infura.io/v3/<project key>"));

Web3j implements the JSON-RPC API client of Ethereum, and its usage is as follows <response> = web3.<operation>.send(). E.g:

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();

} catch(IOException ex) {
  throw new RuntimeException("Error whilst sending json-rpc requests", ex);
}

Note: The serialization of JSON-RPC requests may cause IOException, so you need to deal with it.

6. Complete Ethereum blockchain Java access code

The following code shows the complete Java program code to connect to the Ethereum node and execute the JSON-RPC API call.

//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:8545"));
    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);
    }
  }
}

Right-click the file Main.java and select Run As> Java Application to run this Java program. You should see the following on the console;

Connecting to Ethereum ...
Successfuly connected to Ethereum
Client version: Geth/v1.8.22-omnibus-260f7fbd/linux-amd64/go1.11.1
Block number: 7983049
Gas price: 3000000000

The screenshot is as follows:

Insert picture description here


Original link: Java Ethereum development environment setup — Huizhi.com

Guess you like

Origin blog.csdn.net/shebao3333/article/details/106868007