Start learning free

LESSON 4 OF 173 · BACKEND: HOW THE WEB WORKS

Check the Status First

Practice

Every answer from a server starts with a status code: a number that says how the request went. 200 OK means the body holds what you asked for. 404 Not Found means there is nothing at that address. A 404 is not a crash: the request went out, and the server answered.

The status tells you what the body holds, so check it before you use the body. In Java, response.statusCode() gives it. Here is the idea on another page of the supplier:

HttpRequest request = HttpRequest.newBuilder(URI.create(SUPPLIER + "/catalog?page=1")).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
    System.out.println("Got the page");
}

Your script looks up three product ids: 3, 99 and 5. The supplier has no product 99, so it answers 404, and its body holds an error instead of a product. Reading product.get("name") from that body would give null, and the script would print null costs null.

GET /prices/3   →  200  {"name": "Lamp", "price": 14, …}
GET /prices/99  →  404  {"error": "No product with that id"}
GET /prices/5   →  200  {"name": "Plant", "price": 6, …}

Your script must print:

Product 3 - status 200
Lamp costs 14
Product 99 - status 404
No such product at the supplier
Product 5 - status 200
Plant costs 6

Your task: loop over productIds, send a request for /prices/ followed by each id, and print the id and its status code. For a 200, read the body into a map and print the product's name, " costs " and its price. For a 404, print "No such product at the supplier".


Assignment
Follow the Coding Tutorial to request each product, print its status code and handle the 200 and 404 answers.


Hint
+ joins the number onto the text by itself, so SUPPLIER + "/prices/" + productId is the whole address. Print the status before the if, and start the else if line with the } that closes the if.


STEP 1 OF 9
    Ctrl + Enter to check