TRX官网HTTP完整接口文档链接:https://tronprotocol.github.io/documentation-zh/api/http/#http-api
实现下面之前需要先搭建TRX钱包节点进行设置 关于搭建具体请看上一篇文章
代码只贴了查询余额和生成地址的方式,其他接口请参考源码文档进行对接
需要添加工具类:hutool
依赖方式
- Maven:
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.7</version>
</dependency>
- Gradle:
compile 'cn.hutool:hutool-all:5.4.7'
下面直接上代码:
// TODO: URL
public static final String FULLNODEURL = "http://ip地址:端口/wallet/";
// TODO: 生成地址数量
public static final int NUMBER = 2;
public static void main(String[] args) throws Exception {
//查询TRC20代币余额
//BigDecimal getTrc20Balance = balanceOf("TWDDUF6JxKgC8ErsprDQtf5znhJUYtF43N", COINADDRESS);
//查询TRX余额
BigDecimal getTrxBalance = getTrxBalance("TWDDUF6JxKgC8ErsprDQtf5znhJUYtF43N");
System.out.println(getTrxBalance.toPlainString());
//TRC-20转账
//sendTrc20TransactionTest();
//TRX转账
//collectTrx();
}
/**
* 通过节点生成地址
*/
public static JSONArray getAddress() {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < NUMBER; i++) {
String body = HttpUtil.post(FULLNODEURL + "generateaddress", "");
JSONObject jsonBody = JSONObject.parseObject(body);
String privateKey = jsonBody.getString("privateKey");
String address = jsonBody.getString("address");
String hexAddress = jsonBody.getString("hexAddress");
JSONObject jsonAddress = new JSONObject();
jsonAddress.put("privateKey", privateKey);
jsonAddress.put("address", address);
jsonAddress.put("hexAddress", hexAddress);
jsonArray.add(jsonAddress);
}
return jsonArray;
}
/**
* 查询TRX余额
* @param address
* @return
* @throws Exception
*/
public static BigDecimal getTrxBalance(String address) throws Exception {
JSONObject jsonObject = new JSONObject();
jsonObject.put("address", address);
jsonObject.put("visible", true);
String json = jsonObject.toJSONString();
String body = HttpRequest.post(FULLNODEURL + "getaccount").body(json).execute().body();
JSONObject jsonBody = JSONObject.parseObject(body);
if (jsonBody.isEmpty()) {
return BigDecimal.ZERO;
} else {
BigDecimal balance = new BigDecimal(jsonBody.getBigInteger("balance")).divide(new BigDecimal("1000000"));
return balance;
}
}
查询成功!
有遇到疑惑的可加好友交流 QQ号:1172243570