简体   繁体   English

设置cURL以调用REST API

[英]Set up a cURL to call a REST API

I've been trying to setup a cURL call to a REST API for days (see my previous topics) and still it won't work... 我一直在尝试设置对REST API的cURL调用几天(请参阅我以前的主题),但仍然无法正常工作...

Though, what I need is fairly simple: 虽然,我需要的很简单:
I need make a call with the POST method to an url. 我需要使用POST方法调用url。 This URL requires authentication (which, according to the documentation, I should pass by HTTP headers using the GET function). 此URL需要身份验证(根据文档,我应该使用GET函数通过HTTP标头传递身份验证)。 And on top of that, I need to set a body ( <searchCriteriaSorting></searchCriteriaSortin ) and I should use the Content-Type: application/xml and the Charset=UTF-8 . 最重要的是,我需要设置一个主体( <searchCriteriaSorting></searchCriteriaSortin ),并且应该使用Content-Type: application/xmlCharset=UTF-8

Nothing more, nothing less. 仅此而已。 According to the author of the API, it should be very simple. 根据API的作者,它应该非常简单。 But me, nor my colleagues manage to build a solid connection to this API. 但是我,我的同事也没有设法建立与此API的牢固连接。

To use authentication you can use the cURL option CURLOPT_USERPWD. 要使用身份验证,可以使用cURL选项CURLOPT_USERPWD。 To define that you'd like to use POST use cURL option CURLOPT_POST. 要定义您要使用POST,请使用cURL选项CURLOPT_POST。 To set the required headers you can use use cURL option CURLOPT_HTTPHEADER. 要设置所需的标题,可以使用cURL选项CURLOPT_HTTPHEADER。 Finally you have to set the body of the HTTP POST request be using cURL option CURLOPT_POSTFIELDS, whereby $xml is your XML content. 最后,您必须使用cURL选项CURLOPT_POSTFIELDS设置HTTP POST请求的主体,其中$ xml是您的XML内容。

/* init cURL session */
$ch = curl_init();
...
/* set password */
curl_setopt($ch, CURLOPT_USERPWD, "loginname:passwort");
/* use method POST */
curl_setopt($ch, CURLOPT_POST, true);
/* set header 'Content-Type' */
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=UTF-8'));
/* set HTTP body */
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
...
/* exec cURL request */
curl_exec($ch);
curl_close($ch);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM