callOutSample.cls
代码语言:javascript复制public with sharing class callOutSample {
public static Map<String, Object> getInfoCallOut() {
Map<String, Object> results = new Map<String, Object>();
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);
System.debug('>>>debuglog>>>>>>>>>>response>>>>>>>>>>>>>' response);
// If the request is successful, parse the JSON response.
if(response.getStatusCode() == 200) {
// Deserialize the JSON string into collections of primitive data types.
results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
}
return results;
}
public static Map<String, Object> setInfoCallOut(String inputJson) {
Map<String, Object> results = new Map<String, Object>();
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');
// Set the body as a JSON object
request.setBody(inputJson);
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());
results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
}
return results;
}
}
callOutApex.cls
代码语言:javascript复制public with sharing class callOutApex {
public static void getInfoCallOut() {
Map<String, Object> results = callOutSample.getInfoCallOut();
// // 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);
}
}
public static void setInfoCallOut() {
Map<String, Object> results = callOutSample.setInfoCallOut('{"name":"mighty moose"}');
// // 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);
}
}
}