Another Salesforce blog!!!

Salesforce, Apex

Get Data from HttpRequest/HttpResponse


First Authorize Endpoint Addresses:

Authorize Endpoint Addresses

We love security at Salesforce! So, any time you make a callout to an external site we want to make sure that it is authorized. We can’t have code calling out willy-nilly to any endpoint without prior approval. Before you start working with callouts, update the list of approved sites for your org on the Remote Site Settings page.
We’ll be using the following endpoints in this module, so go ahead and add them now. If you forget to add an endpoint, trust me, you’ll get a reminder when you try to run your code. We’ll be making calls to the following sites.

https://th-apex-http-callout.herokuapp.com
https://th-apex-soap-service.herokuapp.com
Authorize both of these endpoint URLs by following these steps.

1. From Setup, enter Remote Site Settings in the Quick Find box, then click Remote Site Settings.
2. Click New Remote Site.
3. For the remote site name, enter animals_http.
4. For the remote site URL, enter https://th-apex-http-callout.herokuapp.com. This URL authorizes all subfolders for the endpoint, like 1. https://th-apex-http-callout.herokuapp.com/path1 and https://th-apex-http-callout.herokuapp.com/path2.
5. For the description, enter Trailhead animal service: HTTP.
6. Click Save & New.
7. For the second remote site name, enter animals_soap.
8. For the remote site URL, enter https://th-apex-soap-service.herokuapp.com.
9. For the description, enter Trailhead animal service: SOAP.
10. Click Save.  

Get Data from a Service

the Developer Console, select Debug | Open Execute Anonymous Window

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) {
    // Deserialize 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);
    }
}

public class InTheArea {
    @AuraEnabled
        public static String getLocal (String searchTerm, Decimal lat, Decimal lon) {
        String url = 'https://th-yelp-locator.herokuapp.com/search?address=' + lat +','+ lon + '&term=' + EncodingUtil.urlEncode(searchTerm, 'UTF-8');
        HttpRequest req = new HttpRequest();
        Http http = new Http();
        req.setMethod('GET');    
        req.setEndpoint(url);
        HTTPResponse res = http.send(req);
        return res.getBody();   
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*