以太坊的Java用戶端使用__Java

來源:互聯網
上載者:User
準備工作 已經安裝好以太坊用戶端或是以太坊叢集 安裝jdk8開發環境,web3j需要在java 8的環境才能運行 引入jar包
<dependency>  <groupId>org.web3j</groupId>  <artifactId>core</artifactId>  <version>2.2.1</version></dependency>
串連以太坊用戶端

使用web3j的api串連

public class Web3JClient {    private static String ip = "http://ip地址:8545/";    private Web3JClient(){}    private volatile static Web3j web3j;    public static Web3j getClient(){        if(web3j==null){            synchronized (Web3JClient.class){                if(web3j==null){                    web3j = Web3j.build(new HttpService(ip));                }            }        }        return web3j;    }}

使用Parity的api串連

public class ParityClient {    private static String ip = "http://ip地址:8545/";    private ParityClient(){}    private static class ClientHolder{        private static final Parity parity = Parity.build(new HttpService(ip));    }    public static final  Parity getParity(){        return ClientHolder.parity;    }}
賬戶操作

1.建立賬戶POJO

public class AccountInfo {    private String userName;    private String phone;    private String address;    private String school;    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String getPhone() {        return phone;    }    public void setPhone(String phone) {        this.phone = phone;    }    public String getAddress() {        return address;    }    public void setAddress(String address) {        this.address = address;    }    public String getSchool() {        return school;    }    public void setSchool(String school) {        this.school = school;    }}

2.賬戶相關操作

public class Account {    private static  Parity parity = ParityClient.getParity();    private static Web3j web3j = Web3JClient.getClient();    /**     * Life     * Like this     * Like that     * Also     * It's not the same with you think     * @Author lzh     *     */    public List<String> getAccountlist(){        try{            return  parity.personalListAccounts().send().getAccountIds();        }catch (Exception e){            e.printStackTrace();        }        return null;    }    public String createAccount(String accountName,String password,AccountInfo accountInfo){        try {            NewAccountIdentifier newAccountIdentifier = parity.personalNewAccount(password).send();            if(newAccountIdentifier!=null){                String accountId = newAccountIdentifier.getAccountId();                parity.personalSetAccountName(accountId,accountName);                Map<String,Object> account = new HashMap<String,Object>();                account.put(accountId,accountInfo);                parity.personalSetAccountMeta(accountId,account);                return  accountId;            }        } catch (Exception e) {            e.printStackTrace();        }        return null;    }    public PersonalAccountsInfo.AccountsInfo getAccountInfo(String accountId){        try{            PersonalAccountsInfo personalAccountsInfo = parity.personalAccountsInfo().send();            return  personalAccountsInfo.getAccountsInfo().get(accountId);        }catch (Exception e){            e.printStackTrace();        }        return null;    }    public BigInteger getBalance(String accountId){        try {            DefaultBlockParameter defaultBlockParameter = new DefaultBlockParameterNumber(58);            EthGetBalance ethGetBalance =  parity.ethGetBalance(accountId,defaultBlockParameter).send();            if(ethGetBalance!=null){                return ethGetBalance.getBalance();            }        }catch (Exception e){            e.printStackTrace();        }        return null;    }}
賬戶測試
public class AccountTest {    public static void main(String args[]) {        getBalance();    }    public static void getBalance(){        Account account = new Account();        BigInteger ba = account.getBalance("0xcee1086eabd4cac10f6658eeffcdc66ad7565450");        System.out.print(ba);    }    public static  void queryAccount(){        Account account = new Account();        List<String> accounts = account.getAccountlist();        for(String accountId:accounts){            System.out.println(accountId);        }    }    public void createAccount(){            Account account = new Account();            AccountInfo accountInfo = new AccountInfo();            accountInfo.setPhone("229787499");            accountInfo.setAddress("世寧大廈");            accountInfo.setSchool("buaa");            accountInfo.setUserName("lzh");            String accountId = account.createAccount("lzh","123456",accountInfo);            System.out.println("註冊賬戶成功:"+accountId);//        PersonalAccountsInfo.AccountsInfo accountsInfo = account.getAccountInfo("0xad7bbca86e02e503076b06931e05938e51e49fb9");//        System.out.println(accountsInfo.toString());    }}
交易操作
public class Trade {    private static final Logger logger = LoggerFactory.getLogger(Trade.class);    private static BigInteger nonce = new BigInteger("0");    private static BigInteger gasPrice = new BigInteger("1");    private static BigInteger gasLimit = new BigInteger("50");    private Parity parity = ParityClient.getParity();    public boolean trasfer(String accountId,String passsword,String toAccountId, BigDecimal amount)  {        Transaction transaction = Transaction.createEtherTransaction(accountId,null,null,null,toAccountId,amount.toBigInteger());        try{            EthSendTransaction ethSendTransaction =parity.personalSignAndSendTransaction(transaction,passsword).send();            if(ethSendTransaction!=null){                String tradeHash = ethSendTransaction.getTransactionHash();                logger.info("賬戶:[{}]轉賬到賬戶:[{}],交易hash:[{}]",accountId,toAccountId,tradeHash);            }        }catch (Exception e){            logger.error("賬戶:[{}]交易失敗!",accountId,e);        }        return false;    }}
交易測試
public class TradeTest {    public static void main(String args[]){        Trade trade = new Trade();        trade.trasfer("賬戶a的hash碼","abc123","賬戶b的hash碼",new BigDecimal(100));    }}
其他

有問題,或者想瞭解更多區塊鏈的資訊,請留言。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.