How to communicate between Java and bitcoind?

7

2

I am having problems communicating between Java and bitcoind - every JSON RPC library I try has some issues. Can anyone provide a working implementation of even the most basic JSON RPC communication between Java and bitcoind ?

ThePiachu

Posted 2013-02-09T14:05:48.473

Reputation: 41 594

There's a bitcoin library for java... That could be why few people are working on a JSON RPC for java.lurf jurv 2013-02-10T16:40:17.550

Answers

7

Here's an early experimental client I had played around with a while back. It supports getInfo, getBalance and getNewAddress, and can easily be expanded. In order to run it, the credentials for your local bitcoind have to match the values in the client class:

httpclient.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8332),
                    new UsernamePasswordCredentials("btc", "123"));

Feel free to use this code in any way, but understand that it's only 5 minutes of work on a start, not a realistic client implementation. Hope it helps you generate some ideas!

cdelargy

Posted 2013-02-09T14:05:48.473

Reputation: 86

4

You are also very welcome to try out https://github.com/clanie/bitcoind-client - it is in early development, but already supports almost all the methods provided by bitcoind.

Claus Nielsen

Posted 2013-02-09T14:05:48.473

Reputation: 41

3

I had the same issue and created an implementation here: https://github.com/johannbarbie/BitcoindClient4J

JohBa

Posted 2013-02-09T14:05:48.473

Reputation: 31

3

Because this seems like a collection of links, I will just add another one:

https://github.com/priiduneemre/btcd-cli4j

user2084795

Posted 2013-02-09T14:05:48.473

Reputation: 247

2

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

It uses Htmlunit instead of Apache Http Library, which makes it a bit easy to understand and extend.

I actually wrote & tested it for Litecoin for one of my projects. But it has been extended to support bitcoin and all the RPC methods are available.

coding_idiot

Posted 2013-02-09T14:05:48.473

Reputation: 153

2

seba

Posted 2013-02-09T14:05:48.473

Reputation: 121

1

Since I could not find working code snippet anywhere, here is a complete working example (in Scala):

First I created a helper object:

import java.net.URL
import java.net.HttpURLConnection
import org.apache.commons.io.IOUtils

object CurlJsonData {
  def curl(url:String, jsonEncodedString:String) = {
    val httpcon = new URL(url).openConnection.asInstanceOf[HttpURLConnection]
    httpcon.setDoOutput(true);
    httpcon.setRequestProperty("Content-Type", "application/json");
    httpcon.setRequestProperty("Accept", "application/json");
    httpcon.setRequestMethod("POST");
    httpcon.connect;

    val outputBytes = jsonEncodedString.getBytes("UTF-8");

    // 'using' method from: https://stackoverflow.com/a/5218279/243233

    using(httpcon.getOutputStream){os =>
      os.write(outputBytes)
    }
    val code = httpcon.getResponseCode
    val isError = code >= 400 && code <= 500
    val resp = using{
      if (isError) httpcon.getErrorStream else httpcon.getInputStream
    }{is =>
      val writer = new StringWriter;
      IOUtils.copy(is, writer, "UTF-8");
      writer.toString;
    }
    httpcon.disconnect
    if (isError) throw new Exception(
      s"Resp code $code. Error: ${resp.take(200)}"
    ) else resp
  }
}

Then, I used it as follows:

import java.net.Authenticator
import java.net.PasswordAuthentication

val rpcuser = "alice";
val rpcpassword = "secret";

Authenticator.setDefault(
  new Authenticator {
    override def getPasswordAuthentication:PasswordAuthentication = {
      new PasswordAuthentication (rpcuser, rpcpassword.toCharArray)
    }
  }
)  

CurlJsonData.curl(
  "http://localhost:8332", 
  """{"method":"getblockchaininfo","params":[],"id":1,"jsonrpc":"1.0"}"""
) 

Jus12

Posted 2013-02-09T14:05:48.473

Reputation: 1 243

0

If Scala is not your thing, here is Jus12's code in Kotlin:

package com.my.blockchainparser

import java.net.Authenticator
import java.net.PasswordAuthentication
import java.net.URL
import java.net.HttpURLConnection

fun main(args: Array<String>) {
    val rpcuser = "user"
    val rpcpassword = "password"
    Authenticator.setDefault(object : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(rpcuser, rpcpassword.toCharArray())
        }
    })

    System.out.println(curl(
            "http://localhost:8332",
            """{"method":"getblockchaininfo","params":[],"id":1,"jsonrpc":"1.0"}"""
    ))
}

fun curl(url:String, jsonEncodedString:String): String {
    val httpcon = URL(url).openConnection() as HttpURLConnection
    httpcon.setDoOutput(true);
    httpcon.setRequestProperty("Content-Type", "application/json");
    httpcon.setRequestProperty("Accept", "application/json");
    httpcon.setRequestMethod("POST");
    httpcon.connect();

    val outputBytes = jsonEncodedString.toByteArray();

    httpcon.getOutputStream().use {
        it.write(outputBytes)
    }
    val code = httpcon.getResponseCode()
    val isError = code >= 400 && code <= 500
    val text = (if (isError) httpcon.getErrorStream() else httpcon.getInputStream())
            ?.bufferedReader()?.use {
        it.readText()
    } ?: "no connection"
    if (isError) throw Exception(
            "Resp code $code. Error: ${text.take(200)}"
    )
    return text
}

Giszmo

Posted 2013-02-09T14:05:48.473

Reputation: 200