用PHP执行curl请求



我试图使用curl调用API(直接从我的应用程序的后端)。这是我第一次使用它,所以我摸索着学习如何使用它。文档说这是请求:

curl --location -g --request POST '{{url}}/api/rest/issues/' 
--header 'Authorization: {{token}}' 
--header 'Content-Type: application/json' 
--data-raw '{
"summary": "This is a test issue",
"description": "This is a test description",
"category": {
"name": "General"
},
"project": {
"name": "project1"
}
}'

如果我从终端执行它,这应该是代码(如果我做对了)。如果我想移动到php脚本中执行它我需要把它转换成这样的格式:

<?php
$pars=array(
'nome' => 'pippo',
'cognome' => 'disney',
'email' => 'pippo@paperino.com',
);
//step1
$curlSES=curl_init(); 
//step2
curl_setopt($curlSES,CURLOPT_URL,"http://www.miosito.it");
curl_setopt($curlSES,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curlSES,CURLOPT_HEADER, false); 
curl_setopt($curlSES, CURLOPT_POST, true);
curl_setopt($curlSES, CURLOPT_POSTFIELDS,$pars);
curl_setopt($curlSES, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curlSES, CURLOPT_TIMEOUT,30);
//step3
$result=curl_exec($curlSES);
//step4
curl_close($curlSES);
//step5
echo $result;
?>

我将适应我的需要。这是正确的吗?有没有其他方法可以让它像文档中的curl请求一样简单?

我会使用Guzzle这样的HTTP客户端。

$client = new GuzzleHttpClient();
$response = $client->request('POST', 'http://www.miosito.it', [
'form_params' => [
'nome' => 'pippo',
'cognome' => 'disney',
'email' => 'pippo@paperino.com',
]
]);
echo (string) $response->getBody();

有几种方法可以实现curl。你的代码看起来不错,你也可以试试我的代码。

$pars=array(
'nome' => 'pippo',
'cognome' => 'disney',
'email' => 'pippo@paperino.com',
);

如果有时你需要发送json编码的参数,那么使用下面的行。

// $post_json = json_encode($pars);

Curl代码如下

$apiURL = 'http://www.miosito.it';
$ch = @curl_init();
@curl_setopt($ch, CURLOPT_POST, true);
@curl_setopt($ch, CURLOPT_POSTFIELDS, $pars);
@curl_setopt($ch, CURLOPT_URL, $apiURL);
@curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = @curl_exec($ch);
$status_code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors = curl_error($ch);
@curl_close($ch);
echo "<br>Curl Errors: " . $curl_errors;
echo "<br>Status code: " . $status_code;
echo "<br>Response: " . $response;

如果您还需要什么,请告诉我。