在 Apex 中使用 HTTP POST 设置参数

Posted

技术标签:

【中文标题】在 Apex 中使用 HTTP POST 设置参数【英文标题】:Set parameters with HTTP POST in Apex 【发布时间】:2013-06-25 14:06:05 【问题描述】:

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

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

有什么方法可以让我将 HTTP 类型设置为 POST 吗?

【问题讨论】:

“GET”和“POST”cs.tut.fi/~jkorpela/forms/methods.html和w3schools.com/tags/ref_httpmethods.asp的根本区别 【参考方案1】:

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

@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/sendComment?commentTitle=示例标题&textBody=这是一条评论

【讨论】:

【参考方案2】:

可以,但是你需要使用 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);

有关更多信息,请参阅Salesforce documentation。

【讨论】:

我是否必须设置任何请求标头,如this link中所述 没有。你需要使用 req.setbody('id=' + someId '&text=' + content);如此处所述***.com/questions/14551194/… 不要忘记将 Content-Type 设置为 application/x-www-form-urlencoded 像这样 req.setHeader('Content-Type','application/x-www-form-urlencoded') 和 urlEncode 你的数据。

以上是关于在 Apex 中使用 HTTP POST 设置参数的主要内容,如果未能解决你的问题,请参考以下文章

Apex 中 PageReference 的使用

Apache HTTP 客户端,POST 请求。如何正确设置请求参数?

HTTP请求中Get和Post请求的区别?

HTTP 中 GET 与 POST 的区别

HTTP协议-GET/POST请求

android中post请求怎么传输内容