gpt4 book ai didi

php - 通过 Curl/PHP 查询 API

转载 作者:可可西里 更新时间:2023-10-31 23:09:22 25 4
gpt4 key购买 nike

我正在查看 Parse.com REST API 并使用 PHP 使用的 Curl 包装器进行调用。

原始 Curl 代码(有效):

curl -X GET \
-H "X-Parse-Application-Id: myApplicationID" \
-H "X-Parse-REST-API-Key: myRestAPIKey" \
https://api.parse.com/1/classes/Steps

PhP 代码(有效):

$ch = curl_init('https://api.parse.com/1/classes/Steps');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id: myApplicationID',
'X-Parse-REST-API-Key: myRestAPIKey',
'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_exec($ch);
curl_close($ch);

这很好,但现在当我尝试添加查询约束时:

原始 Curl 代码(有效):

curl -X GET \
-H "X-Parse-Application-Id: myApplicationID" \
-H "X-Parse-REST-API-Key: myRestAPIKey" \
-G \
--data-urlencode 'where={"steps":9243}' \
https://api.parse.com/1/classes/Steps

唉,我们最终得出了我的问题 - 与上述代码类似的 php 是什么?

PHP 代码(不工作):

$ch = curl_init('https://api.parse.com/1/classes/Steps');

$query = urlencode('where={"steps":9243}');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('X-Parse-Application-Id: myApplicationID',
'X-Parse-REST-API-Key: myRestAPIKey',
'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);

curl_exec($ch);
curl_close($ch);

错误响应:

Object ( [code] => 107 [error] => invalid json: where%3D%7B%22steps%22%3A9243%7D )

最佳答案

您的最后一个 PHP 示例已将请求从 GET 更改为 POST。在查询字符串而不是 POST 正文中传递您的参数。尝试:

$query = urlencode('where={"steps":9243}');
$ch = curl_init('https://api.parse.com/1/classes/Steps?'.$query);

curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'X-Parse-Application-Id: myApplicationID',
'X-Parse-REST-API-Key: myRestAPIKey',
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_exec($ch);
curl_close($ch);

关于php - 通过 Curl/PHP 查询 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18026258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com