11

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?

1

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Do I have to set any of the request headers, as described in this link
No. You need to use req.setbody('id=' + someId '&text=' + content); as described here stackoverflow.com/questions/14551194/… 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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.