首页 > 解决方案 > 使用 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 请求一样简单?

标签: phpcurl

解决方案


有几种方法可以做卷曲。你的代码看起来不错,你也可以试试我的代码。

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

如果有时您需要发送 json 编码参数,请使用以下行。

// $post_json = json_encode($pars);

卷曲代码如下

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

如果您还需要其他东西,请告诉我。


推荐阅读