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 Prag Prog topics Top

yulkin
your book suggests to use Image.toByteData() to convert image to bytes, however I get the following error: "the getter ‘toByteData’ isn’t...
New
jamis
The following is cross-posted from the original Ray Tracer Challenge forum, from a post by garfieldnate. I’m cross-posting it so that the...
New
sdmoralesma
Title: Web Development with Clojure, Third Edition - migrations/create not working: p159 When I execute the command: user=&gt; (create-...
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
patoncrispy
I’m new to Rust and am using this book to learn more as well as to feed my interest in game dev. I’ve just finished the flappy dragon exa...
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
rainforest
Hi, I’ve got a question about the implementation of PubSub when using a Phoenix.Socket.Transport behaviour rather than channels. Before ...
New
a.zampa
@mfazio23 I’m following the indications of the book and arriver ad chapter 10, but the app cannot be compiled due to an error in the Bas...
New
mcpierce
@mfazio23 I’ve applied the changes from Chapter 5 of the book and everything builds correctly and runs. But, when I try to start a game,...
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

AstonJ
Or looking forward to? :nerd_face:
New
siddhant3030
I’m thinking of buying a monitor that I can rotate to use as a vertical monitor? Also, I want to know if someone is using it for program...
New
DevotionGeo
I know that -t flag is used along with -i flag for getting an interactive shell. But I cannot digest what the man page for docker run com...
New
AstonJ
You might be thinking we should just ask who’s not using VSCode :joy: however there are some new additions in the space that might give V...
New
Rainer
My first contact with Erlang was about 2 years ago when I used RabbitMQ, which is written in Erlang, for my job. This made me curious and...
New
AstonJ
Continuing the discussion from Thinking about learning Crystal, let’s discuss - I was wondering which languages don’t GC - maybe we can c...
New
New
AstonJ
If you get Can't find emacs in your PATH when trying to install Doom Emacs on your Mac you… just… need to install Emacs first! :lol: bre...
New
PragmaticBookshelf
Author Spotlight: Sophie DeBenedetto @SophieDeBenedetto The days of the traditional request-response web application are long gone, b...
New
PragmaticBookshelf
A Ruby-Centric Chat with Noel Rappin @noelrappin Once you start noodling around with Ruby you quickly figure out, as Noel Rappi...
New

Latest in PragProg

View all threads ❯