Salesforce Apex Rest Callout 取得JSON形式的数据

以下边网站为例,用浏览器打开URL:https://th-apex-http-callout.herokuapp.com/animals,会返回JSON形式数据

代码语言:javascript
复制
{
    "animals": [
        "majestic badger",
        "fluffy bunny",
        "scary bear",
        "chicken"
    ]
}

1.把URL添加到Salesforce中

2.ApexClass中实现Service中取得JSON形式的数据。

callOutSample.cls

代码语言:javascript
复制
public with sharing class callOutSample {
    public static Map<String, Object> getCalloutInfo() {
        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;
    }
}

3.调用上边做成的Apex方法,查看结果

callOutApex.cls

代码语言:javascript
复制
public with sharing class callOutApex {
    public callOutApex() {
        Map<String, Object> results = callOutSample.getCalloutInfo();
        // // 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);
        }
    }
}

4.匿名块执行