Getting Bitcoin Price

Once the project is created and the dependencies added, we will move on to get the Bitcoin price. The CoinDesk Bitcoin Price Index Web Service is available at the following address:

https://api.coindesk.com/v1/bpi/currentprice.json

A first call to this API in a Web browser allows us to see the look of its rendering:

JSON returned by the BPI Web Service

At the level of the main class of our program, we create a client property of type OkHttpClient. This object is the entry point of the OkHttp API and will then allow us to launch our request to the Web Service.

The request is represented by a Request object to which we enter the endpoint of the CoinDesk Bitcoin Price Index. The latter is stored in a static variable BITCOIN_PRICE_ENDPOINT.

To execute this request with the previously created OkHttpClient instance, we use its newCall method to which we pass the Request object we just built as an input. It then remains to call the enqueue method which takes as input an object of type Callback. The use of this interface allows us to decouple the processing of the result of the request from the actual call.

All this gives the following code within a loadBitcoinPrice method:

private void loadBitcoinPrice(Callback callback) {

Request request = new Request.Builder().url(BITCOIN_PRICE_ENDPOINT).build();

client.newCall(request).enqueue(callback);

}

As our program must continuously watch the price of Bitcoin, it is necessary that this call to the Bitcoin Price Index Web Service be made at regular intervals.

To implement this operation, Java offers the Timer API. I will therefore define a TimerTask object within which I will make the call to the loadBitcoinPrice method. The execution of this TimerTask is scheduled every minute following the call to the schedule method of the Timer instantiated for the occasion.

So we have the following code: