【问题标题】:REST API service: how to call it correctly via PHP curl?REST API 服务:如何通过 PHP curl 正确调用它?
【发布时间】:2016-11-27 17:14:35
【问题描述】:

假设我有一个正在运行的服务 API,它响应如下网址:

http://example.com/param/1

它用于 get 和 post 动词。 Param=1 是考虑的参数

我应该如何正确执行 curl 请求以传递参数(POST)?

如果我浏览:http://example.com/param/1 我会得到预期的响应(GET)

但是,如果我执行以下操作,它将无法正常工作:

$service_url = 'http://example.com/';
$curl = curl_init($service_url);
$curl_post_data = array('param'=>1);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
    die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);

即使像下面这样改变它也行不通:

$service_url = 'http://example.com/param/1';
$curl = curl_init($service_url);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
    die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);

这反而有效:但我想它仍然是一个 GET

$service_url = 'http://example.com/param/1';
$curl = curl_init($service_url);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
    $info = curl_getinfo($curl);
    curl_close($curl);
    die('error occured during curl exec. Additional info: ' . var_export($info));
}
curl_close($curl);
$decoded = json_decode($curl_response);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
    die('error occured: ' . $decoded->response->errormessage);
}
echo 'response ok!';
var_export($decoded->response);

【问题讨论】:

    标签: php api rest curl


    【解决方案1】:
    $service_url = 'http://example.com/param/1';     
    $ch = curl_init($service_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "param1=value1&param2=value2&..");
    $response = curl_exec($ch);
    curl_close($ch);
    

    【讨论】:

    • 不,不是。 param=1 是要传递的参数...您列出的帖子字段不是必需的(param1,param2....)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-09
    • 2020-04-12
    • 2015-11-17
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多