Start learning free

LESSON 9 OF 173 · BACKEND: HOW THE WEB WORKS

When the Server Says No in Java

Practice

A server doesn't accept every request. When something is wrong in the request, like a missing field or a value that makes no sense, it answers with a status in the 400s, most often 400 Bad Request. The server works fine: sending the same request again gets the same answer. client.send doesn't throw on a 400: you get a normal response, and your code decides what to do.

A refusal still has a body, and many APIs put an "error" message in it that says what to fix. A success and a refusal don't have the same keys, and a Java map's get quietly gives null for a missing key. So check the status code before you read the body. For example, after posting a sign-up with an empty email to a sign-up service:

HttpResponse<String> reply = client.send(signup, HttpResponse.BodyHandlers.ofString());
if (reply.statusCode() == 400) {
    Map<String, Object> answer = new ObjectMapper().readValue(reply.body(), Map.class);
    System.out.println("Fix this: " + answer.get("error"));
}

Your program sends the supplier three orders: a good one, one with a quantity of 0, and one with no quantity at all.

POST /orders  {"product_id": 1, "quantity": 3}  →  201  {"order_id": 1001, …}
POST /orders  {"product_id": 1, "quantity": 0}  →  400  {"error": "product_id and a quantity of 1 or more are required"}
POST /orders  {"product_id": 2}                 →  400  {"error": "product_id and a quantity of 1 or more are required"}

It must print:

Status: 201
Order placed: 1001
Status: 400
Refused: product_id and a quantity of 1 or more are required
Status: 400
Refused: product_id and a quantity of 1 or more are required

Your task: post each order in orders to /orders and print its status. Then print the order id if the status is 201, and the server's error message otherwise.


Assignment
Follow the Coding Tutorial to send the three orders and print what the supplier says about each one.


Hint
Read the body with readValue(response.body(), Map.class), then use if (response.statusCode() == 201) and an else. Read data.get("order_id") only inside the if: a refusal has an "error" key instead.


STEP 1 OF 10
    Ctrl + Enter to check

    Web Bad Request in Java

    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free