Every response carries a number that says what happened: the status code. The
number is not random. Its first digit names a family, and the family tells you
whether the call worked, whether the request was wrong, or whether the service
broke.
A family is a range, not a single value. 200, 201 and 204 are all successes,
and 400, 401, 403 and 404 are all client errors. So compare the code with a
range instead of with one number:
Integer code = response.getStatusCode();
if (code >= 200 && code < 300) {
// the request worked
} else if (code >= 400 && code < 500) {
// the request was wrong
} else if (code >= 500 && code < 600) {
// the service broke
}
Read the status code off the response, never off the number you asked for. A
service may answer with a code you did not ask for. DummyJSON answers a status
code it does not support with 500, so a request for 100 comes back as a server
error rather than as 100.
A 204 is a success and it carries no body at all. Parsing an empty string
throws System.JSONException, so check the status code first and read the
body only when there is one to read.
The first mistake is comparing the status code with one value, so a 201 falls
through and looks like a failure. The second is reading the body before
checking the status code. The third is trusting the number you asked for
instead of the code that came back.