Created
May 30, 2023 22:52
-
-
Save jeffdonthemic/57ac82cd2d9498ff78c98b14393a1b7a to your computer and use it in GitHub Desktop.
HTTP Requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AnimalsCallouts { | |
public static HttpResponse makeGetCallout() { | |
Http http = new Http(); | |
HttpRequest request = new HttpRequest(); | |
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals'); | |
request.setMethod('GET'); | |
HttpResponse response = http.send(request); | |
// If the request is successful, parse the JSON response. | |
if(response.getStatusCode() == 200) { | |
// Deserializes the JSON string into collections of primitive data types. | |
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody()); | |
// Cast the values in the 'animals' key as a list | |
List<Object> animals = (List<Object>) results.get('animals'); | |
System.debug('Received the following animals:'); | |
for(Object animal: animals) { | |
System.debug(animal); | |
} | |
} | |
return response; | |
} | |
public static HttpResponse makePostCallout() { | |
Http http = new Http(); | |
HttpRequest request = new HttpRequest(); | |
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals'); | |
request.setMethod('POST'); | |
request.setHeader('Content-Type', 'application/json;charset=UTF-8'); | |
request.setBody('{"name":"mighty moose"}'); | |
HttpResponse response = http.send(request); | |
// Parse the JSON response | |
if(response.getStatusCode() != 201) { | |
System.debug('The status code returned was not expected: ' + | |
response.getStatusCode() + ' ' + response.getStatus()); | |
} else { | |
System.debug(response.getBody()); | |
} | |
return response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment