function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Prateek Kumar 11Prateek Kumar 11 

Make HTTP request from a VF Button


I have requirement where I would like to call an apex class method which makes a HTTP callout to an external service. What is the best way to achieve this?
The HTTP service would return some data that I would like to update on the record from which the VF page button is clicked, and display alerts like initiated/completed/error.
Also, shall this method be made asynchronous or is it fine to make a synchronous request in such scenarios considering the the callback doesn't take much time.

Please help.
Thanks in advance.
Edgar MoranEdgar Moran
Hi, you can maybe use remote apex in order to achieve this, for example:

In your controller:
    global static String Send_Message(Set<Id> some_ids){

        //Generating a Http variable
        Http h = new Http();        
        //Generating the http request
        HttpRequest req = new HttpRequest();  

        JSONGenerator gen = JSON.createGenerator(true);  

        /*:::: REQUEST PARAMETERS :::::*/
        req.setHeader('Content-Type', 'application/json;application/x-www-form-urlencoded;charset=UTF-8');        
        HttpResponse res = h.send(req);
        return res.getBody();


in your javascript code;
function sendMessage(){
           console.log('check your result: '+result);


your visualforce can invoke the action with Jquery or usign pure javascript onclick event, it depends how you feel more confortable.

Hope it helps.