Sub topic 6
Reading the response
This chapter assumes you can already send a request with Http, HttpRequest and HttpResponse, and that you know the common HTTP status code families. Here you learn what an HttpResponse gives you and how to check it before you use the body.
What a response contains
Http.send() returns an HttpResponse. It holds three things you will use most often:
| Method | Returns | Use it for |
|---|---|---|
| `getStatusCode()` | `Integer` | Deciding what happened, such as 200, 404 or 500 |
| `getStatus()` | `String` | A readable reason, such as `OK` or `Not Found`, for logs and messages |
| `getHeader(name)` | `String` | One header value, or `null` if the header is absent |
| `getHeaderKeys()` | `String[]` | All header names the server sent |
| `getBody()` | `String` | The payload as text |
| `getBodyAsBlob()` | `Blob` | Binary payloads such as files or images |
A non-2xx status does not throw an exception. send() only throws a CalloutException when no response arrives at all, for example on a timeout or a failed connection. A 404 or 500 comes back as a normal HttpResponse, and your code must check it.
Check the status first
Always test the status code before you touch the body. An error response usually has a body too, but it is an error message and not the data you asked for.
public with sharing class ResponseReader {
public class ApiException extends Exception {}
public static String readJson(HttpResponse res) {
Integer code = res.getStatusCode();
if (code < 200 || code >= 300) {
throw new ApiException(
'Request failed: ' + code + ' ' + res.getStatus()
);
}
String contentType = res.getHeader('Content-Type');
if (contentType == null || !contentType.containsIgnoreCase('application/json')) {
throw new ApiException('Expected JSON but got: ' + contentType);
}
return res.getBody();
}
}Checking Content-Type is cheap. It catches the case where a proxy or login page returns HTML with a 200 status, which would otherwise fail later with a confusing JSON parse error.
Reading headers
Use getHeader when you know the name. Use getHeaderKeys when you want to see everything the server sent, which helps when debugging.
public static void logHeaders(HttpResponse res) {
for (String key : res.getHeaderKeys()) {
if (key != null) {
System.debug(key + ': ' + res.getHeader(key));
}
}
}The key != null guard matters. The returned list can contain a null entry, and passing it to string concatenation or getHeader would give you a misleading result.
Redirects are not followed for you
Apex does not follow a 3xx redirect automatically. You get the 301 or 302 response itself, and the new address is in the Location header. If you expect redirects, read that header and send a second request. The new endpoint must still be authorized, through a Named Credential or a Remote Site Setting.
Text, binary and size
Use getBody() for JSON, XML and plain text. For files, use getBodyAsBlob(), because converting binary data to a String can corrupt it. The whole response is held in memory, so it counts against the heap size limit. Ask the API for only the fields or page size you need.
Exercise
A callout returns status 503 with an HTML error page as the body. Does Http.send() throw a CalloutException, and what should your code do before calling JSON.deserialize?
Show answer
No. send() returned a response, so it throws nothing. Your code must check getStatusCode() and stop on a non-2xx value, for example by throwing its own exception that includes the code and getStatus(). Only after a 2xx status, and ideally a matching Content-Type, should it parse the body.