RPC实现BTC 查余额 发交易

package com.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import com.googlecode.jsonrpc4j.Base64;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 
 */
public class BtcRpc {
    protected static final String  user = "";          //rpc接口用户名
    protected static final String  password = "";//rpc接口密码
    private static String cred = ”;
    private static String url = null;
    private static JSONObject json;
    
    
    
    public static void main(String[] args) {

    }
    


    /**
     * 根据交易签名发送交易
     * @param sign 交易签名
     * @return
     */
    public static String sendBTCSign(String sign) {
        String msg="error:发送交易失败";
        try {
            JSONObject result = JSONObject.fromObject(sendRawTransaction(sign));
            System.out.println("发送签名结果:"+result);
            //如果转账成功
            if(result.get("result")==null){
                //获取错误信息
                msg=net.sf.json.JSONObject.fromObject(result.get("error")).getString("message");
            }else{
                String txid=result.getString("result");
                if (txid.length() == 64) {
                    msg="success:".concat(txid);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return msg;
    }

    /**
     * 导入地址
     * @param address
     * @return
     */
    public static String importAddress(String address) {
        Object[] str = {address};
        json = new JSONObject();
        try {
            json.put("method", "importaddress");
            json.put("params", str);
            json.put("id", Object.class);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String result =  post(json);
        return result;
    }

    /**
     * 根据hash查询交易详情
     * @param hash
     * @return
     */
    public static String getRawTransaction(String hash) {
        Object[] str = {hash,1};
        json = new JSONObject();
        try {
            json.put("method", "getrawtransaction");
            json.put("params", str);
            json.put("id", Object.class);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String result =  post(json);
        return result;
    }

    /**
     * 获取块高
     * @return
     */
    public static String getBlockCount() {
        Object[] str = {};
        json = new JSONObject();
        try {
            json.put("method", "getblockcount");
            json.put("params", str);
            json.put("id", Object.class);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String result =  post(json);
        return result;
    }

  
  /**
  * 根据块hash获取块信息
  *
  * @param blockHash
  * @returnlock
  */
  public static Object getBlock(String blockHash) {
  Object[] str = {blockHash, 1};
  json = new JSONObject();
  try {
  json.put("method", "getblock");
  json.put("params", str);
  json.put("id", Object.class);
  } catch (JSONException e) {
e.printStackTrace();
  }
   System.out.println(post(json));
  return post(json);
  }

/** * 返回所有账户的交易 * @return */ public static String listTransactions(){ Object[] str = {}; json = new JSONObject(); try { json.put("method", "listsinceblock"); json.put("params", str); json.put("id", Object.class); } catch (JSONException e) { e.printStackTrace(); } String result = post(json); return result; } /** * 获取btc中间费率 * @return */ public static int getBtcHalfFree(){ //fastestFee-最快费率 halfHourFee-中间费率 hourFee-最低费率 int free=0; try { net.sf.json.JSONObject object=net.sf.json.JSONObject.fromObject(get("https://bitcoinfees.21.co/api/v1/fees/recommended")); free=Integer.parseInt(object.get("halfHourFee").toString()); } catch (Exception e) { e.printStackTrace(); } return free; } /** * 根据块高度获取块哈希 * @param height * @return */ public static String getBlockHash(int height){ Object[] str = {height}; json = new JSONObject(); try { json.put("method", "getblockhash"); json.put("params", str); json.put("id", Object.class); } catch (JSONException e) { e.printStackTrace(); } return post(json); } /** * 查询代币余额 * @param address * @param contactAddress * @return */ public static double getTokenBalance(String address, int contactAddress) { double price=0; try { Object[] str = {address,contactAddress}; json = new JSONObject(); json.put("method", "omni_getbalance"); json.put("params", str); json.put("id", Object.class); net.sf.json.JSONObject object=net.sf.json.JSONObject.fromObject(post(json)); price=object.getJSONObject("result").getDouble("balance"); } catch (Exception e) { } return price; } /** * 根据签名发送交易 * @param sign 交易签名 * @return * @throws JSONException */ public static String sendRawTransaction(String sign) throws JSONException{ Object[] str = {sign}; JSONObject json = new JSONObject(); json.put("method", "sendrawtransaction"); json.put("params", str); json.put("id", Object.class); String result = post(json); return result; } /** * https://insight.bitpay.com/api/addr/"+address+"/utxo * 拉取比特大陆的utxo(参考https://wiki.trezor.io/) * @param address * @return */ public static JSONObject getBtcUtxo(String address){ JSONObject jsonObject = null; try { jsonObject = JSONObject.fromObject(getHttpResponse("https://bitcoinblockexplorers.com/api/addrs/"+address+"/utxo"));; } catch (Exception e) { e.printStackTrace(); } return jsonObject; }


  
/**
* 查询代币交易
*
* @param txHash
* @return
*/
public static String getTokentransaction(String txHash) {
String transaction = "";
try {
Object[] str = {txHash};
json = new JSONObject();
json.put("method", "omni_gettransaction");
json.put("params", str);
json.put("id", Object.class);
net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(post(json));
transaction = object.getJSONObject("result").toString();
} catch (Exception e) {
}
return transaction;
}

/**
* 查询代币交易
*
* @param
* @return
*/
public static String getTokenSend(String fromaddress, String toaddress, Integer propertyid, BigDecimal amount) {
String transaction = "";
try {
Object[] str = {fromaddress, toaddress, propertyid, amount};
json = new JSONObject();
json.put("method", "omni_send");
json.put("params", str);
json.put("id", Object.class);
net.sf.json.JSONObject object = net.sf.json.JSONObject.fromObject(post(json));
transaction = object.getJSONObject("result").toString();
} catch (Exception e) {
}
return transaction;
}

/**
* 查询代币交易
*
* @param
* @return
*/
public static JSONObject getlistblocktransactions(long index) {
net.sf.json.JSONObject object = null;
try {
Object[] str = {index};
json = new JSONObject();
json.put("method", "omni_listblocktransactions");
json.put("params", str);
json.put("id", Object.class);
object = net.sf.json.JSONObject.fromObject(post(json));
} catch (Exception e) {
}
return object;
}

/** * https://bitcoinblockexplorers.com/API/addr/" + address + "/balance
    * 获取地址余额 * @param address * @return
*/
public static JSONObject getBalance(String address){
    JSONObject jsonObject = null;
    try {
      jsonObject = JSONObject.fromObject(getHttpResponse("https://blockchain.info/unspent?active="+address));
    } catch (Exception e) {
    e.printStackTrace();
    }
    return jsonObject;
  }


/** * rpc请求post * @param json * @return */
public static String post(JSONObject json) {  
    HttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);   
    post.setHeader("Content-Type", "application/json")  
    post.setHeader("Authorization", "Basic " + cred);   
    String result = "";   
    try
{
    StringEntity s = new StringEntity(json.toString(), "utf-8");
    s.setContentEncoding(
new BasicHeader(HTTP.CONTENT_TYPE,"application/json")); post.setEntity(s);
    // 发送请求
    
HttpResponse httpResponse = client.execute(post);
    // 获取响应输入流 InputStream inStream = httpResponse.getEntity().getContent();
    BufferedReader reader
= new BufferedReader(new InputStreamReader( inStream, "utf-8"));
    StringBuilder strber
= new StringBuilder(); String line = null;
      
while ((line = reader.readLine()) != null)
      strber.append(line); inStream.close(); result
= strber.toString();

   }
catch (Exception e) {
      e.printStackTrace();
   }
    
return result;
  }


/** * get请求 * @param url * @return */
public static String get(String url) {
   HttpClient client
= HttpClients.createDefault();
   HttpGet
get = new HttpGet(url);
   get.setHeader("Content-Type", "application/json"); String result = "";

  
try {
    
// 发送请求
    
HttpResponse httpResponse = client.execute(get);
   
// 获取响应输入流
    InputStream inStream = httpResponse.getEntity().getContent();
    BufferedReader reader
= new BufferedReader(new InputStreamReader( inStream, "utf-8"));
    StringBuilder strber
= new StringBuilder(); String line = null;
    
while ((line = reader.readLine()) != null) strber.append(line);
    inStream.close(); result
= strber.toString();
  }
catch (Exception e) { e.printStackTrace(); }
    
return result;
  }



/** * 获取http请求返回结果 * @param allConfigUrl * @return */
public static String getHttpResponse(String allConfigUrl) {
  BufferedReader
in = null;
  StringBuffer result
= null;
  
try {
    URI uri
= new URI(allConfigUrl);
    URL url
= uri.toURL();
    URLConnection connection
= url.openConnection();
    connection.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty(
"Charset", "utf-8");
    connection.setRequestProperty(
"User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
    connection.connect();
    connection.setConnectTimeout(
60*1000);//超时60秒 result = new StringBuffer();
    in = new BufferedReader(new InputStreamReader( connection.getInputStream()));
    String line;
    
while ((line = in.readLine()) != null) {
    result.append(line);
  }
    return result.toString();
  }
catch (Exception e) {
    e.printStackTrace();
} finally {
  try {
    
if (in != null) {
    in.close();
  }
}
catch (Exception e2) {
  return null;
}
}

https://blog.csdn.net/jiujiuming/article/details/103988712

 

posted @ 2021-07-08 14:44  panda's  阅读(899)  评论(0编辑  收藏  举报