php - 使用 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 请求一样简单?
解决方案
有几种方法可以做卷曲。你的代码看起来不错,你也可以试试我的代码。
$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;
如果您还需要其他东西,请告诉我。
推荐阅读
- python-3.x - 你如何调整条形图上的间距和它的 xtick 标签?
- azure - 如何在 Azure PowerShell 中获取所有资源参数详细信息
- php - PHP从带有href链接和标签的mysql DB获取结果
- html - 在Angular中打印所选行的行号
- node.js - 如何让 node.js body-parser 抱怨有效负载太大
- azure - 覆盖 Chrome 对具有空白相同站点属性的 cookie 的新行为
- c# - 使用 C# Datastax CassandraCSharpDriver.Graph 获取连接到已知顶点的所有未知顶点
- javascript - client.guilds.each 似乎不是一个函数 [Discord.js]
- javascript - 动态注入内容脚本 - Chrome 扩展
- vim - 有没有办法给 vim 导航键起别名?