Showing posts with label Post Request From Apex Class. Show all posts
Showing posts with label Post Request From Apex Class. Show all posts

Monday, July 18, 2016

How to make a post or get request to some other server from apex class

1. Go to "setup/Develop/Apex Class"
2. Click "new"
3. Write code as following:


public class ApexClass_1 {
    @Future(callout=true)
    public static void c1(String Account_ID) {
        String name = '';
        try {
            HttpRequest req = new HttpRequest();
            req.setEndpoint('http://www.yahoo.com');
            req.setMethod('POST');
            req.setBody('Account_ID='+EncodingUtil.urlEncode(Account_ID, 'UTF-8')+'&other_param='+EncodingUtil.urlEncode('OTHER PARAM VALUE', 'UTF-8'));
            req.setCompressed(true);

            /* If you want to send basic authentication */
            String username = 'myname';
            String password = 'mypwd';
            Blob headerValue = Blob.valueOf(username + ':' + password);
            String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);

            Http http = new Http();
            HTTPResponse res = http.send(req);
            name = 'Status_Code=' + res.getStatusCode();
            String responseBody = res.getBody();
        }
        catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);
            name = ('Error=' + e.getMessage()).substring(0, 20);
        }

        /* Reading account object */
        Account account = [SELECT Id FROM Account WHERE Id = :Account_ID];
        account.Name = name;
        update op;
    }
}


4. Go to "setup/Security Controls/Remote Site Settings"
5. Click "New remote site" & enter the URL that you want to invoke from apex class.
6. Invoke method "ApexClass_1.c1" from wherever you want.

7. An example of invoke url in salesforce from apex sObjects trigger options
8. Go to "setup/Customize/Accounts/Triggers"
9. Click "new"
10. Write the following code:

trigger TriggerActionName on Account (before insert, after insert, after delete) {
    if (Trigger.isInsert) {
        if (Trigger.isAfter) {
            for (Account a : Trigger.New) {
                ApexClass_1.c1(a.Id);
            }
        }
    }
}


11. Once you create a new account the url would be invoked in a short time (Also you could write code for update & delete)
12. Apex trigger documentation: https://developer.salesforce.com/trailhead/en/apex_triggers/apex_triggers_intro