Bitcoin Forum

Bitcoin => Development & Technical Discussion => Topic started by: dunand on February 12, 2012, 05:27:11 AM



Title: bitcoind json-rpc with Java
Post by: dunand on February 12, 2012, 05:27:11 AM
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


Title: Re: bitcoind json-rpc with Java
Post by: M1SHO on February 28, 2014, 06:20:15 AM
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.




Title: Re: bitcoind json-rpc with Java
Post by: myusuario on February 28, 2014, 03:32:44 PM
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....


Title: Re: bitcoind json-rpc with Java
Post by: clanie on February 28, 2014, 04:00:02 PM
I implemented a java-wrapper for most of the api a while back - you can find it here:
https://github.com/clanie/bitcoind-client


Title: Re: bitcoind json-rpc with Java
Post by: kamronk on March 25, 2015, 04:28:51 PM
For anyone else who comes across this, hopefully I can help you :)

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<String> fileInfo = new ArrayList<String>();
            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.


Title: Re: bitcoind json-rpc with Java
Post by: coinpr0n on March 31, 2015, 08:17:37 PM
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/


Title: Re: bitcoind json-rpc with Java
Post by: kamronk on April 01, 2015, 06:49:07 AM
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.


Title: Re: bitcoind json-rpc with Java
Post by: coinpr0n on April 01, 2015, 12:13:46 PM
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.


Title: Re: bitcoind json-rpc with Java
Post by: ScripterRon on April 01, 2015, 02:34:11 PM
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 (https://github.com/ScripterRon/BitcoinMonitor) for an example.


Title: Re: bitcoind json-rpc with Java
Post by: kamronk on April 01, 2015, 03:33:47 PM
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 (https://github.com/ScripterRon/BitcoinMonitor) for an example.

Right, that's what I'm using in my example above :)