Set parameters with HTTP POST in Apex

Sushant Rao picture Sushant Rao · Jun 27, 2013 · Viewed 28.9k times · Source

I'm trying to set POST content using Apex. The example below sets the variables using GET

  PageReference newPage = Page.SOMEPAGE;
  SOMEPAGE.getParameters().put('id', someID);
  SOMEPAGE.getParameters().put('text', content);

Is there any way for me to set the HTTP type as POST?

Answer

Moti Korets picture Moti Korets · Jul 3, 2013

Yes but you need to use HttpRequest class.

String endpoint = 'http://www.example.com/service';
String body = 'fname=firstname&lname=lastname&age=34';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setbody(body);
Http http = new Http();
HTTPResponse response = http.send(req);

For additional information refer to Salesforce documentation.