Salesforce 在Apex中使用HTTP POST设置参数

Salesforce 在Apex中使用HTTP POST设置参数,salesforce,force.com,Salesforce,Force.com,我正在尝试使用Apex设置帖子内容。下面的示例使用GET设置变量 PageReference newPage = Page.SOMEPAGE; SOMEPAGE.getParameters().put('id', someID); SOMEPAGE.getParameters().put('text', content); 有没有办法将HTTP类型设置为POST 是,但您需要使用HttpRequest类 String endpoint = 'http://www.example.c

我正在尝试使用Apex设置帖子内容。下面的示例使用GET设置变量

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

有没有办法将HTTP类型设置为POST

是,但您需要使用HttpRequest类

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);

有关更多信息,请参阅。

以下apex类示例将允许您在post请求的查询字符串中设置参数-

@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"}]');
    }
}
上述API类的URL如下所示-


/services/apexrest/sendcoment?commentTitle=Sample title&textBody=这是一条注释

关于“GET”和“POST”之间的根本区别,我是否必须设置任何请求头,如No中所述。您需要使用req.setbody('id='+someId'&text='+content);如本文所述,不要忘记将内容类型设置为application/x-www-form-urlencoded,如下面的req.setHeader('Content-Type','application/x-www-form-urlencoded'),并对数据进行urlEncode。