Supplier, Consumer functional interface and httpclient to get and output Bitcoin info

Transcribed from the original LinkedIn image post.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.function.Consumer;
import java.util.function.Supplier;

class Day11 {
    public static void main(String[] args) throws IOException, InterruptedException {
        Supplier<String> jsonStringSupplier = () -> getBitcoinInfoAsString();
        String str = jsonStringSupplier.get();

        Consumer<String> consumeString = s -> System.out.println(s);
        consumeString.accept(str);
    }

    public static String getBitcoinInfoAsString() {
        HttpClient httpClient = HttpClient.newHttpClient();

        HttpRequest httpRequest = HttpRequest
            .newBuilder()
            .uri(URI.create("https://api.coindesk.com/v1/bpi/currentprice.json"))
            .header("Accept", "application/json")
            .build();

        HttpResponse<String> httpResponse = null;
        try {
            httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return httpResponse.body().toString();
    }
}

The original LinkedIn graphic is preserved below.

Day 11 LinkedIn post