9

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?

Sushant Rao
  • 464
  • 1
  • 4
  • 11
  • The fundamental differences between "GET" and "POST" http://www.cs.tut.fi/~jkorpela/forms/methods.html and http://www.w3schools.com/tags/ref_httpmethods.asp – Andrii Muzychuk Jun 28 '13 at 17:00

2 Answers2

17

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.

caleb.breckon
  • 1,265
  • 16
  • 41
Moti Korets
  • 3,458
  • 2
  • 23
  • 33
  • Do I have to set any of the request headers, as described in [this link](http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_pages_pagereference.htm) – Sushant Rao Jul 08 '13 at 03:58
  • 5
    No. You need to use req.setbody('id=' + someId '&text=' + content); as described here http://stackoverflow.com/questions/14551194/how-are-parameters-sent-in-an-http-post-request dont forget to set Content-Type to application/x-www-form-urlencoded like this req.setHeader('Content-Type','application/x-www-form-urlencoded') and urlEncode your data. – Moti Korets Jul 08 '13 at 06:43
0

The following apex class example will allow you to set parameters in the query string for a post request -

@RestResource(urlmapping = '/sendComment/*')

global without sharing class postComment {

@HttpPost
global static void postComment(){

    //create parameters 

    string commentTitle = RestContext.request.params.get('commentTitle');
    string textBody = RestContext.request.params.get('textBody');       

    //equate the parameters with the respective fields of the new record

    Comment__c thisComment = new Comment__c(
        Title__c = commentTitle,
        TextBody__c = textBody, 

    );

    insert thisComment; 


    RestContext.response.responseBody = blob.valueOf('[{"Comment Id": 
    '+JSON.serialize(thisComment.Id)+', "Message" : "Comment submitted 
    successfully"}]');
    }
}

The URL for the above API class will look like -

/services/apexrest/sendComment?commentTitle=Sample title&textBody=This is a comment