通过 Curl/PHP 查询 API [英] Querying API through Curl/PHP
本文介绍了通过 Curl/PHP 查询 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在查看 Parse.com REST API 并使用 PHP 使用的 Curl 包装器进行调用.
I'm looking at the Parse.com REST API and making calls using the Curl wrapper PHP uses.
原始卷曲代码(有效):
Raw Curl code(works):
curl -X GET \
-H "X-Parse-Application-Id: myApplicationID" \
-H "X-Parse-REST-API-Key: myRestAPIKey" \
https://api.parse.com/1/classes/Steps
PhP 代码(有效):
PhP code(works):
$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);
那太好了,但现在当我尝试添加查询约束时:
Thats good and dandy, but now when I try to add a query constraint:
Raw Curl 代码(有效):
Raw Curl code(works):
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 是什么?
Alas, we ultimately arrive at my question- What is the php analogue to the above code?
PHP 代码(不起作用):
PHP code(does not work):
$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 正文中传递您的参数.试试:
Your last PHP example has changed the request to a POST from a GET. Pass your parameters in the query string instead of the POST body. Try:
$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);
这篇关于通过 Curl/PHP 查询 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文