将REST curl命令转换为Apex Request

时间:2016-07-21 07:13:25

标签: rest curl apex

我有一个REST API调用的curl示例,如下所示

curl https://api.endpoint.com/api_action.json \
-u key:secret \
-d 'message=Hello World' \
-d id=12345

现在我正在尝试使用Apex HttpRequest类复制它,但我不确定如何将选项传递给调用。

到目前为止我所拥有的内容如下

HttpRequest req = new HttpRequest();
req.setEndpoint(https://api.endpoint.com/api_action.json);
req.setMethod('POST');
// what goes in these
req.setHeader(stuff);
req.setBody(stuff);

Http http = new Http();
HttpResponse res = http.send(req);

2 个答案:

答案 0 :(得分:1)

来自@sfdcfox answer

鉴于此评论:

curl -i -X POST --data“first_name = test& last_name = testlast& email=test@test.com& phone = 1234567& company = Ac meInc& years_in_business = 3& amount = 4000& dealer_id = 524b2833f7494317db000001 “https://example.com/webform/start/

您需要的代码大概是:

String payload='first_name=test&last_name=testlast&email=test@test.com&phone=1234567&company=Ac‌​meInc&years_in_business=3&amount=4000&dealer_id=524b2833f7494317db000001';
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint('https://example.com/webform/start/');
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setHeader('Content-Length',String.valueOf(payload.length()));
req.setBody(payload);
Http binding = new Http();
HttpResponse res = binding.send(req);

答案 1 :(得分:0)

当您使用APEX时,可以使用内置的apex_web_service.make_rest_request来执行此操作:

declare
  v_clob clob;
begin
  v_clob := apex_web_service.make_rest_request( 
                        p_url            => <your URL>,
                        p_http_method    => 'POST',
                        p_body           => <whatever body>,
                        p_username       => 'username',
                        p_password       => 'password' );
  htp.p(v_clob);
end;