Start learning free

LESSON 5 OF 173 · BACKEND: HOW THE WEB WORKS

Send a Query String

Practice

A query string is the part of a URL after the ?. It carries options for the path as name=value pairs, joined with &. The server reads them and shapes its answer: /prices?max_price=5 asks the supplier for the products that cost 5 or less.

Java's HttpClient has no separate place for options: you write the query string into the address yourself, right after the path. response.uri() shows the address the request really went to:

HttpRequest request = HttpRequest.newBuilder(URI.create(SUPPLIER + "/catalog?page=2")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.uri());   // http://127.0.0.1:8001/catalog?page=2

The supplier filters its list before it answers, so the products that cost more never leave the server. For /prices with max_price set to 5, your script must print:

URL: http://127.0.0.1:8001/prices?max_price=5
Mug costs 5
Notebook costs 3
Pen costs 1

Your task: send a request for /prices?max_price=5, print "URL: " and response.uri(), then read the JSON body into a list of maps and print each product that came back: its name, " costs " and its price.


Assignment
Follow the Coding Tutorial to send the query string, print the URL the request went to and print the products the supplier sent back.


Hint
The query string goes in the same text as the path, right after it, with no space: "/prices?max_price=5". The answer is a JSON list, so read it with List.class and loop over it.


STEP 1 OF 6
    Ctrl + Enter to check