Author

Topic: bitcoind json-rpc with Java (Read 3511 times)

sr. member
Activity: 297
Merit: 250
Bitcoin is to money what the internet was to media
April 01, 2015, 10:33:47 AM
#10
Well, for what I'm building I needed the code to be more modular to work with all cryptos that are QT based (all except NXT and its clones), so the json-rpc interface was the best choice for connecting to bitcoin, as json-rpc is supported as a standard.
I use the json-simple library to access the bitcoind RPC functions.  Take a look at Request.java in BitcoinMonitor for an example.

Right, that's what I'm using in my example above Smiley
full member
Activity: 136
Merit: 120
April 01, 2015, 09:34:11 AM
#9
Well, for what I'm building I needed the code to be more modular to work with all cryptos that are QT based (all except NXT and its clones), so the json-rpc interface was the best choice for connecting to bitcoin, as json-rpc is supported as a standard.
I use the json-simple library to access the bitcoind RPC functions.  Take a look at Request.java in BitcoinMonitor for an example.
hero member
Activity: 910
Merit: 1000
April 01, 2015, 07:13:46 AM
#8
Any reason why BitcoinJ is not an option? It's a complete Java Bitcoin library and has options to connect to local bitcoind instance IIRC. https://bitcoinj.github.io/

Well, for what I'm building I needed the code to be more modular to work with all cryptos that are QT based (all except NXT and its clones), so the json-rpc interface was the best choice for connecting to bitcoin, as json-rpc is supported as a standard.

OK, yeah that makes sense then. Some altcoins have made good forks of the BitcoinJ library (like Dogecoin) but not all of them. I can see why you're going that route if working with other coins too.
sr. member
Activity: 297
Merit: 250
Bitcoin is to money what the internet was to media
April 01, 2015, 01:49:07 AM
#7
Any reason why BitcoinJ is not an option? It's a complete Java Bitcoin library and has options to connect to local bitcoind instance IIRC. https://bitcoinj.github.io/

Well, for what I'm building I needed the code to be more modular to work with all cryptos that are QT based (all except NXT and its clones), so the json-rpc interface was the best choice for connecting to bitcoin, as json-rpc is supported as a standard.
hero member
Activity: 910
Merit: 1000
March 31, 2015, 03:17:37 PM
#6
Any reason why BitcoinJ is not an option? It's a complete Java Bitcoin library and has options to connect to local bitcoind instance IIRC. https://bitcoinj.github.io/
sr. member
Activity: 297
Merit: 250
Bitcoin is to money what the internet was to media
March 25, 2015, 11:28:51 AM
#5
For anyone else who comes across this, hopefully I can help you Smiley

I prototype all my dev in netbeans, and bring it over to eclipse where I do my deployment development (hopefully these terms make sense lol)

Anyways, I needed a pure java solution (no maven bullshit). It's using jar's from apache for HTTP comm:
http://hc.apache.org/downloads.cgi

Download the binary of your choice under the HttpClient 4.4 (GA) section.

You will also need the json-simple jar from Google: (dwnld link in the 'Getting Started' section)
https://code.google.com/p/json-simple/

You will need to point to these jar files in your build configuration for the java project. In netbeans, right click the project in the project explorer, hover over Set Configuration and click on Customize. Then in that menu that pops up, click Libraries in the left pane, and choose "Add JAR/Folder". In eclipse, right click your project, hover over build path and click on Configure Built Path. Then in the pop up menu choose to Add Jars" or "Add external Jars" depending on where your downloaded directory is from apache (I will always copy jars into my actual project so the dependencies are carried from instance to instance, unless security is tighter for whatever reason)

Once you have those jars in your build path, copy/paste these two files into your project:

Note: This is for a windows machine, for linux, change the line:
dir = System.getProperty("user.home") + "\\AppData\\Roaming\\Bitcoin";

To:
dir = System.getProperty("user.home") + "\\.Bitcoin";


Quote from: CryptoConfig
public class CryptoConfig {
    
    private String url;
    private String rpcPort;
    private String rpcUser;
    private String rpcPass;
    
    public CryptoConfig(String urlIN, String rpcPortIN, String rpcUserIN, String rpcPassIN){
        this.url = urlIN;
        this.rpcPort = rpcPortIN;
        this.rpcUser = rpcUserIN;
        this.rpcPass = rpcPassIN;
    }
    
    public CryptoConfig(){
        
    }

    public String getRpcPass() {
        return rpcPass;
    }

    public void setRpcPass(String rpcPass) {
        this.rpcPass = rpcPass;
    }

    public String getRpcPort() {
        return rpcPort;
    }

    public void setRpcPort(String rpcPort) {
        this.rpcPort = rpcPort;
    }

    public String getRpcUser() {
        return rpcUser;
    }

    public void setRpcUser(String rpcUser) {
        this.rpcUser = rpcUser;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
    
    
    
}

Quote from: CommWithWallet
import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class CommWithWallet {

    private int BITCOIN_PORT_NUMBER = 9368;

    public static void main(String[] args) {
        CommWithWallet that = new CommWithWallet();
    }

    public CommWithWallet() {
        System.out.println(CryptoInvoke("BTC", "getbalance"));
    }

    public String CryptoInvoke(String currency, String a_sMethod, Object... a_params) {

        String returnString = "";

        CryptoConfig configDetails = ReadConfig(currency);

//        System.out.println(configDetails.getUrl());
//        System.out.println(configDetails.getRpcPort());
//        System.out.println(configDetails.getRpcUser());
//        System.out.println(configDetails.getRpcPass());
//        System.out.println(a_sMethod);
//        System.out.println(currency);

        try {

            String urlString = configDetails.getUrl() + ":" + configDetails.getRpcPort();
            String signature = "";

            String userPassword = configDetails.getRpcUser() + ":" + configDetails.getRpcPass();
            String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());

            JSONObject paramsJson = new JSONObject();
            paramsJson.put("jsonrpc", "1.0");
            paramsJson.put("id", "1");
            paramsJson.put("method", a_sMethod);

            if (a_params != null) {
                if (a_params.length > 0) {
                    JSONArray paramArray = new JSONArray();
                    for (Object baz : a_params) {
                        paramArray.add(baz);
                    }
                    paramsJson.put("params", paramArray);
                }
            }

            CloseableHttpClient cliente = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(urlString);
            String comando = paramsJson.toJSONString();
            StringEntity entidad = new StringEntity(comando);
            httpPost.setEntity(entidad);
            httpPost.setHeader("Authorization", "Basic " + encoding);
            HttpResponse respuesta = cliente.execute(httpPost);
            BufferedReader rd = new BufferedReader(new InputStreamReader(respuesta.getEntity().getContent()));
            String inputLine = "";
            returnString = "";
            while ((inputLine = rd.readLine()) != null) {
                returnString += inputLine;
            }

        } catch (NumberFormatException ne) {
            // btcAmountString was not a number
            ne.printStackTrace();
        } catch (IOException ne) {
            // btcAmountString was not a number
            ne.printStackTrace();
        }

        return returnString;
    }

    public CryptoConfig ReadConfig(String currency) {

        int portNumber = 0;
        String dir = "";
        String fileLocation = "";

        CryptoConfig config = new CryptoConfig();

        if (System.getProperty("user.home").contains("C:")) {

            if (currency.equals("BTC")) {
                dir = System.getProperty("user.home") + "\\AppData\\Roaming\\Bitcoin";
                portNumber = BITCOIN_PORT_NUMBER;
                fileLocation = dir + "\\bitcoin.conf";
            } else if (currency.equals("")) {
            }

            ArrayList fileInfo = new ArrayList();
            try {
                BufferedReader in = new BufferedReader(new FileReader(fileLocation));
                String inputLine = "";
                while ((inputLine = in.readLine()) != null) {
                    fileInfo.add(inputLine);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(CommWithWallet.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
                System.out.println(fileLocation);
            } catch (IOException ex) {
                Logger.getLogger(CommWithWallet.class.getName()).log(Level.SEVERE, null, ex);
                ex.printStackTrace();
                System.out.println(fileLocation);
            }

            for (String configLine : fileInfo) {

                String configKey = "";
                String configValue = "";
                int index = configLine.indexOf('=');
                if (index > 0) {
                    configKey = configLine.substring(0, index);
                    configValue = configLine.substring(configLine.lastIndexOf('=') + 1);

                    if (configKey.equals("walleturl")) {
                        config.setUrl(configValue);
                    } else if (configKey.equals("rpcport")) {
                        config.setRpcPort(configValue);
                    } else if (configKey.equals("rpcuser")) {
                        config.setRpcUser(configValue);
                    } else if (configKey.equals("rpcpassword")) {
                        config.setRpcPass(configValue);
                    }


                }
            }

        } else {
            //linux
        }

        return config;
    }
}

Now, I do hear from others that this will run into problems when you start doing tricky things involving what I would consider advanced functionality of the QT (anything more than creating addresses, checking balances of addresses, sending coin and inspecting transactions).

To run this, there is a main method in CommWithWallet that creates an instance of itself, and in the constructor you will see the System.out.println() line.
newbie
Activity: 54
Merit: 0
February 28, 2014, 11:00:02 AM
#4
I implemented a java-wrapper for most of the api a while back - you can find it here:
https://github.com/clanie/bitcoind-client
newbie
Activity: 7
Merit: 0
February 28, 2014, 10:32:44 AM
#3
Hi, i would recommend you to use HttpClient to interact with bitcoind.
Example

Code:
CloseableHttpClient cliente = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(urlCnx);
            String comando = "{\"method\":\"getbalance\"}";
            StringEntity entidad = new StringEntity(comando);
            httpPost.setEntity(entidad);
            HttpResponse respuesta = cliente.execute(httpPost);

and then read the response....
sr. member
Activity: 258
Merit: 250
February 28, 2014, 01:20:15 AM
#2
You can try filing an issue else you can try using the below library (I've used it for one of my projects)

https://github.com/coding-idiot/Litecoin-Bitcoin-RPC-Java-Connector

I guess it doesn't implement walletpassphrase, but you can file an issue & hopefully, the developer will look into it or you can just fork and write it yourself.


hero member
Activity: 637
Merit: 502
February 12, 2012, 12:27:11 AM
#1
I'm trying to interact with bitcoind from Java code. I'm using this json-rpc library http://code.google.com/p/jsonrpc4j/.

I can call successfully call methods like getbalance and getaccountaddress but I receive an error 500 when I try to call walletpassphrase. I have no idea why.

Anyone is playing with json-rpc in java? Can you call walletpassphrase? How?


thanks
Jump to: