Bitcoin Forum
December 04, 2016, 06:42:55 PM *
News: To be able to use the next phase of the beta forum software, please ensure that your email address is correct/functional.
 
   Home   Help Search Donate Login Register  
Pages: [1]
  Print  
Author Topic: bitcoind json-rpc with Java  (Read 2839 times)
dunand
Hero Member
*****
Offline Offline

Activity: 625



View Profile
February 12, 2012, 05: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
1480876975
Hero Member
*
Offline Offline

Posts: 1480876975

View Profile Personal Message (Offline)

Ignore
1480876975
Reply with quote  #2

1480876975
Report to moderator
1480876975
Hero Member
*
Offline Offline

Posts: 1480876975

View Profile Personal Message (Offline)

Ignore
1480876975
Reply with quote  #2

1480876975
Report to moderator
Advertised sites are not endorsed by the Bitcoin Forum. They may be unsafe, untrustworthy, or illegal in your jurisdiction. Advertise here.
1480876975
Hero Member
*
Offline Offline

Posts: 1480876975

View Profile Personal Message (Offline)

Ignore
1480876975
Reply with quote  #2

1480876975
Report to moderator
1480876975
Hero Member
*
Offline Offline

Posts: 1480876975

View Profile Personal Message (Offline)

Ignore
1480876975
Reply with quote  #2

1480876975
Report to moderator
M1SHO
Sr. Member
****
Offline Offline

Activity: 260


View Profile
February 28, 2014, 06: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.



The World's First Gold-Backed Crypto Currency INNcoin - http://4thjulycoin.com/
myusuario
Newbie
*
Offline Offline

Activity: 7


View Profile
February 28, 2014, 03:32:44 PM
 #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....
clanie
Jr. Member
*
Offline Offline

Activity: 54



View Profile
February 28, 2014, 04:00:02 PM
 #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
kamronk
Sr. Member
****
Offline Offline

Activity: 297

Bitcoin is to money what the internet was to media


View Profile WWW
March 25, 2015, 04:28:51 PM
 #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<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.

The best place for all bitcoin newbies
http://bitcoinintroduction.com/
coinpr0n
Hero Member
*****
Offline Offline

Activity: 896



View Profile
March 31, 2015, 08: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/

kamronk
Sr. Member
****
Offline Offline

Activity: 297

Bitcoin is to money what the internet was to media


View Profile WWW
April 01, 2015, 06: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.

The best place for all bitcoin newbies
http://bitcoinintroduction.com/
coinpr0n
Hero Member
*****
Offline Offline

Activity: 896



View Profile
April 01, 2015, 12:13:46 PM
 #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.

ScripterRon
Member
**
Offline Offline

Activity: 85


View Profile
April 01, 2015, 02:34:11 PM
 #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.
kamronk
Sr. Member
****
Offline Offline

Activity: 297

Bitcoin is to money what the internet was to media


View Profile WWW
April 01, 2015, 03:33:47 PM
 #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

The best place for all bitcoin newbies
http://bitcoinintroduction.com/
Pages: [1]
  Print  
 
Jump to:  

Sponsored by , a Bitcoin-accepting VPN.
Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!