Set parameters with HTTP POST in Apex
Asked Answered
T

2

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?

Tapes answered 27/6, 2013 at 21:54 Comment(1)
The fundamental differences between "GET" and "POST" cs.tut.fi/~jkorpela/forms/methods.html and w3schools.com/tags/ref_httpmethods.aspRodolforodolph
B
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.

Bricebriceno answered 3/7, 2013 at 8:19 Comment(2)
Do I have to set any of the request headers, as described in this linkTapes
No. You need to use req.setbody('id=' + someId '&text=' + content); as described here #14551694 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.Bricebriceno
M
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

Madagascar answered 28/10, 2019 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.