dtonhofer

dtonhofer

Functional Programming in Java, Second Edition: p.91: Rewrite FinanceData HTTP request method

On page 91, we use a short method to request a stock ticker, class FinanceData

However, this method is based on java.net.URL which has always been broken in several ways, one which being that it doesn’t encode the URL itself. That class is also deprecated in Java 20. The replacement is java.net.URI (since Java 7).

The construction of the query string, while appropriate as an exercise, can also be done better while demonstrating stream use.

Anyway, let’s go. Here is a definitely longer but IMHO nicer replacement:

    public class FinanceData {
        public static BigDecimal getPrice(final String ticker) {
            HttpResponse<String> response;
            try {
                final String scheme = "https";
                final String authority = "eodhistoricaldata.com";
                final String path = String.format("/api/eod/%s.US",ticker);
                final String query =
                        List.of("fmt=json", "filter=last_close", "api_token=OeAFFmMliFG5orCUuwAKQ8l4WWFQ67YX")
                                .stream()
                                .collect(Collectors.joining("&"));
                final String fragment = null;
                final URI uri = new URI(scheme,authority,path,query,fragment);
                System.out.println("Connecting to URI: " + uri);
                HttpClient client = HttpClient.newHttpClient();
                HttpRequest request = HttpRequest.newBuilder().uri(uri).build();
                response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
            } catch(Exception ex) {
                throw new RuntimeException(ex);
            }
            System.out.println("Received status code: " + response.statusCode());
            if (response.statusCode() == 200) {
                System.out.println("Received body: " + response.body());
                // parsing BigDecimal will throw on bad syntax
                return new BigDecimal(response.body());
            }
            else {
                throw new IllegalStateException("Status code was: " + response.statusCode());
            }
        }
    }

Marked As Solved

venkats

venkats

Author of Programming Kotlin, Rediscovering JavaScript (and 6 other titles)

Decided to keep the change minimum here and resolve the deprecation warning. Fixed. Thank you.

Also Liked

venkats

venkats

Author of Programming Kotlin, Rediscovering JavaScript (and 6 other titles)

Practically, given the context of this example code, there is little benefit to the reader to see more code than minimally necessary for this function.

Popular Pragmatic topics Top

jeffmcompsci
Title: Design and Build Great Web APIs - typo “https://company-atk.herokuapp.com/2258ie4t68jv” (page 19, third bullet in URL list) Typo:...
New
HarryDeveloper
Hi @venkats, It has been mentioned in the description of ‘Supervisory Job’ title that 2 things as mentioned below result in the same eff...
New
Chrichton
Dear Sophie. I tried to do the “Authorization” exercise and have two questions: When trying to plug in an email-service, I found the ...
New
swlaschin
The book has the same “Problem space/Solution space” diagram on page 18 as is on page 17. The correct Problem/Solution space diagrams ar...
New
jskubick
I’m running Android Studio “Arctic Fox” 2020.3.1 Patch 2, and I’m embarrassed to admit that I only made it to page 8 before running into ...
New
fynn
This is as much a suggestion as a question, as a note for others. Locally the SGP30 wasn’t available, so I ordered a SGP40. On page 53, ...
New
dsmith42
Hey there, I’m enjoying this book and have learned a few things alredayd. However, in Chapter 4 I believe we are meant to see the “&gt;...
New
EdBorn
Title: Agile Web Development with Rails 7: (page 70) I am running windows 11 pro with rails 7.0.3 and ruby 3.1.2p20 (2022-04-12 revision...
New
SlowburnAZ
Getting an error when installing the dependencies at the start of this chapter: could not compile dependency :exla, "mix compile" failed...
New
roadbike
From page 13: On Python 3.7, you can install the libraries with pip by running these commands inside a Python venv using Visual Studio ...
New

Other popular topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1017 16965 374
New
AstonJ
If it’s a mechanical keyboard, which switches do you have? Would you recommend it? Why? What will your next keyboard be? Pics always w...
New
PragmaticBookshelf
Design and develop sophisticated 2D games that are as much fun to make as they are to play. From particle effects and pathfinding to soci...
New
New
AstonJ
Just done a fresh install of macOS Big Sur and on installing Erlang I am getting: asdf install erlang 23.1.2 Configure failed. checking ...
New
Margaret
Hello content creators! Happy new year. What tech topics do you think will be the focus of 2021? My vote for one topic is ethics in tech...
New
AstonJ
If you are experiencing Rails console using 100% CPU on your dev machine, then updating your development and test gems might fix the issu...
New
PragmaticBookshelf
Build highly interactive applications without ever leaving Elixir, the way the experts do. Let LiveView take care of performance, scalabi...
New
Maartz
Hi folks, I don’t know if I saw this here but, here’s a new programming language, called Roc Reminds me a bit of Elm and thus Haskell. ...
New
First poster: bot
The overengineered Solution to my Pigeon Problem. TL;DR: I built a wifi-equipped water gun to shoot the pigeons on my balcony, controlle...
New

Latest in PragProg

View all threads ❯