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.

Where Next?

Popular Pragmatic Bookshelf topics Top

New
telemachus
Python Testing With Pytest - Chapter 2, warnings for “unregistered custom marks” While running the smoke tests in Chapter 2, I get these...
New
mikecargal
Title: Hands-on Rust: question about get_component (page 295) (feel free to respond. “You dug you’re own hole… good luck”) I have somet...
New
Mmm
Hi, build fails on: bracket-lib = “~0.8.1” when running on Mac Mini M1 Rust version 1.5.0: Compiling winit v0.22.2 error[E0308]: mi...
New
herminiotorres
Hi! I know not the intentions behind this narrative when called, on page XI: mount() |&gt; handle_event() |&gt; render() but the correc...
New
cro
I am working on the “Your Turn” for chapter one and building out the restart button talked about on page 27. It recommends looking into ...
New
oaklandgit
Hi, I completed chapter 6 but am getting the following error when running: thread 'main' panicked at 'Failed to load texture: IoError(O...
New
adamwoolhether
Is there any place where we can discuss the solutions to some of the exercises? I can figure most of them out, but am having trouble with...
New
redconfetti
Docker-Machine became part of the Docker Toolbox, which was deprecated in 2020, long after Docker Desktop supported Docker Engine nativel...
New
SlowburnAZ
Getting an error when installing the dependencies at the start of this chapter: could not compile dependency :exla, "mix compile" failed...
New

Other popular topics Top

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
AstonJ
Do the test and post your score :nerd_face: :keyboard: If possible, please add info such as the keyboard you’re using, the layout (Qw...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
Margaret
Hello everyone! This thread is to tell you about what authors from The Pragmatic Bookshelf are writing on Medium.
1143 25883 760
New
AstonJ
Was just curious to see if any were around, found this one: I got 51/100: Not sure if it was meant to buy I am sure at times the b...
New
husaindevelop
Inside our android webview app, we are trying to paste the copied content from another app eg (notes) using navigator.clipboard.readtext ...
New
sir.laksmana_wenk
I’m able to do the “artistic” part of game-development; character designing/modeling, music, environment modeling, etc. However, I don’t...
New
AstonJ
If you’re getting errors like this: psql: error: connection to server on socket “/tmp/.s.PGSQL.5432” failed: No such file or directory ...
New
AnfaengerAlex
Hello, I’m a beginner in Android development and I’m facing an issue with my project setup. In my build.gradle.kts file, I have the foll...
New
AstonJ
This is a very quick guide, you just need to: Download LM Studio: https://lmstudio.ai/ Click on search Type DeepSeek, then select the o...
New

Latest in Functional Programming in Java, Second Edition

Functional Programming in Java, Second Edition Portal

Sub Categories: