Sub topic 6
Reading the response
This chapter covers what comes back from Http.send(): the status code, the headers, and the body. It assumes you can already build and send a request, and that you know HTTP status codes, basic JSON, and Apex exceptions. Parsing JSON into typed classes and the full error-handling strategy get their own chapters. Here the goal is to read a response safely and decide what to do with it.
What an HttpResponse contains
Http.send() returns an HttpResponse. It is a plain object that holds everything the server sent back. The methods you will use most are:
| Method | Returns | Notes |
|---|---|---|
| `getStatusCode()` | `Integer` | The numeric code, such as 200 or 404. |
| `getStatus()` | `String` | The reason phrase, such as `OK` or `Not Found`. |
| `getBody()` | `String` | The body as text. |
| `getBodyAsBlob()` | `Blob` | The body as raw bytes, for binary content. |
| `getHeader(String key)` | `String` | One header value, or `null` if absent. |
| `getHeaderKeys()` | `String[]` | The names of all headers. |
Always read the status code first. The body only has meaning in light of the status. A 200 response with JSON and a 500 response with an HTML error page both give you a non-empty string from getBody().
A network failure is not a response
A response only exists if the server answered. If the connection fails or times out, send() throws a System.CalloutException and you never get an HttpResponse. So there are two separate failure paths:
- The server answered with a status such as 404 or 503. You get a response and must check the code yourself. Apex does not throw for these.
- The server could not be reached or did not answer in time.
send()throwsCalloutException.
A common mistake is wrapping the call in try/catch and assuming that covers HTTP errors. It does not. A 500 returns normally.
Checking the status code
Compare the code against the codes your endpoint documents, not against a vague "is it OK" test. A service that creates a record usually returns 201, not 200, so a check for == 200 would reject a success.
public with sharing class StatusDemo {
public static Boolean isSuccess(HttpResponse res) {
Integer code = res.getStatusCode();
return code >= 200 && code < 300;
}
public static String describe(HttpResponse res) {
Integer code = res.getStatusCode();
if (code == 200 || code == 201) {
return 'ok';
} else if (code == 204) {
return 'ok, no content';
} else if (code == 401 || code == 403) {
return 'not authorized';
} else if (code == 404) {
return 'not found';
} else if (code == 429) {
return 'rate limited';
} else if (code >= 500) {
return 'server error';
}
return 'unexpected ' + code;
}
}The grouping matters because each class of status calls for a different reaction:
| Range | Meaning | Typical reaction |
|---|---|---|
| 2xx | Success | Read the body, if there is one. |
| 3xx | Redirect | See the next section. |
| 4xx | Your request was wrong | Do not retry unchanged. Fix the data or credentials. |
| 429 | Too many requests | Retry later, honoring `Retry-After` if present. |
| 5xx | The server failed | Often safe to retry later. |
Redirects
A 3xx response tells you the resource lives elsewhere, and the new address is in the Location header. Apex does not follow redirects for you, so a 301 or 302 arrives as an ordinary response. Read Location and send a new request to it. You also need that new host to be authorized (see the earlier chapters on Remote Site Settings and Named Credentials). Cap the number of hops so a redirect loop cannot exhaust your callout limit.
public with sharing class RedirectDemo {
public static HttpResponse getFollowingRedirects(String url, Integer maxHops) {
HttpResponse res;
String current = url;
for (Integer i = 0; i <= maxHops; i++) {
HttpRequest req = new HttpRequest();
req.setEndpoint(current);
req.setMethod('GET');
res = new Http().send(req);
Integer code = res.getStatusCode();
if (code >= 300 && code < 400 && res.getHeader('Location') != null) {
current = res.getHeader('Location');
} else {
return res;
}
}
throw new CalloutException('Too many redirects starting at ' + url);
}
}Each hop counts against the limit on callouts per transaction, so keep maxHops small.
Reading headers
getHeader() returns one value for a name. Header names are case-insensitive in HTTP, but you should confirm how your endpoint behaves in a test instead of assuming. When you do not know which headers arrived, list them with getHeaderKeys().
public with sharing class HeaderDemo {
public static void logHeaders(HttpResponse res) {
for (String key : res.getHeaderKeys()) {
System.debug(key + ': ' + res.getHeader(key));
}
}
public static Integer retryAfterSeconds(HttpResponse res) {
String value = res.getHeader('Retry-After');
if (String.isBlank(value) || !value.isNumeric()) {
return null;
}
return Integer.valueOf(value);
}
}There are three details to know.
getHeaderKeys()can include anullkey. Some responses carry the status line as an unnamed entry. Guard against a null key before you call string methods on it, or skip it.getHeader()returnsnullfor a missing header. Never call methods directly on the result without a check.- If a header is sent more than once,
getHeader()gives you a single value. Do not rely on it to expose every repeated header.
Retry-After can be either a number of seconds or an HTTP date. The helper above handles only seconds and returns null otherwise, which is a safe default.
Checking the content type
Before you parse, confirm the server sent what you expect. Error pages from proxies and gateways are often HTML, and feeding them to a JSON parser produces a confusing JSONException.
public with sharing class ContentTypeDemo {
public static Boolean isJson(HttpResponse res) {
String contentType = res.getHeader('Content-Type');
return contentType != null && contentType.toLowerCase().contains('application/json');
}
}Use contains() rather than equality. The header often includes a charset, as in application/json; charset=utf-8.
Reading the body
getBody() returns a String, and it is the right choice for JSON, XML and plain text. For binary content such as a PDF or an image, use getBodyAsBlob(). Converting binary data through a string can corrupt it.
public with sharing class BodyDemo {
public static Blob downloadFile(String path) {
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Todo_API' + path);
req.setMethod('GET');
HttpResponse res = new Http().send(req);
if (res.getStatusCode() != 200) {
throw new CalloutException('Download failed: ' + res.getStatusCode());
}
return res.getBodyAsBlob();
}
}Empty bodies
A 204 No Content response has no body by design, and some servers also return an empty body with a 200. Calling a JSON parser on an empty string throws. Check for it first:
public with sharing class EmptyBodyDemo {
public static Object parseIfPresent(HttpResponse res) {
String body = res.getBody();
if (res.getStatusCode() == 204 || String.isBlank(body)) {
return null;
}
return JSON.deserializeUntyped(body);
}
}Untyped parsing for a quick look
When you only need one or two values and do not want to define a class, JSON.deserializeUntyped() returns nested Map<String, Object> and List<Object> structures. The next chapter covers typed deserialization, which is the better default for anything you will maintain. Untyped parsing suits exploration and small, stable payloads.
public with sharing class QuickRead {
public static String titleOf(HttpResponse res) {
Map<String, Object> parsed =
(Map<String, Object>) JSON.deserializeUntyped(res.getBody());
return (String) parsed.get('title');
}
}The casts here fail with a TypeException if the shape differs from what you expect, so the status and content-type checks above should run first.
Limits that apply to the body
The response body counts against the heap size limit, because Apex holds it in memory as a string. A very large payload can fail with a heap error even though the callout succeeded. A single callout also has a maximum response size, and the platform rejects a body that exceeds it. If an endpoint can return large result sets, ask it for pages of data through a query parameter, and process one page per callout.
A complete reading routine
This method combines the checks from the chapter. It returns the body only when the response is a successful JSON reply, and otherwise throws an exception that names the status and a short slice of the body for diagnosis.
public with sharing class ResponseReader {
public class ResponseException extends Exception {}
public static String readJson(HttpResponse res) {
Integer code = res.getStatusCode();
String body = res.getBody();
if (code < 200 || code >= 300) {
String snippet = body == null ? '' : body.abbreviate(200);
throw new ResponseException(
'HTTP ' + code + ' ' + res.getStatus() + ': ' + snippet);
}
if (code == 204 || String.isBlank(body)) {
return null;
}
String contentType = res.getHeader('Content-Type');
if (contentType == null || !contentType.toLowerCase().contains('json')) {
throw new ResponseException('Expected JSON but got ' + contentType);
}
return body;
}
}Trimming the body with abbreviate(200) keeps log lines and exception messages short. It also reduces the chance of writing sensitive data from a large response into a log.
Common mistakes
- Treating any non-exception result as success. A 4xx or 5xx response returns normally.
- Comparing the status to 200 only, which rejects valid 201 and 204 replies.
- Parsing the body before checking the status or content type.
- Calling
getBody()on a binary response and then using the string. - Calling methods on the result of
getHeader()without a null check. - Expecting Apex to follow redirects.
Exercise
A callout returns without throwing an exception, and getStatusCode() is 503. A teammate says the try/catch around send() will handle this case. Is the teammate right, and what should the code do?
Show answer
No. send() throws CalloutException only when no response arrives, such as a connection failure or timeout. A 503 is a normal HttpResponse, so the catch block never runs. The code must check getStatusCode() itself. Since 503 is a 5xx status, the code can treat it as a temporary server failure, log the status and a short body slice, and throw an exception or schedule a retry.
Exercise
An endpoint returns a 200 status, but your JSON parse throws a JSONException. Name two checks on the response that help find the cause.
Show answer
Check the Content-Type header, since a proxy or gateway may have sent an HTML page instead of JSON. Check whether the body is empty or blank, since parsing an empty string fails. Logging a short slice of the body with abbreviate() also shows what actually arrived.