2015-12-02 59 views
0

你好:我正在尝试使用curl_init进行API调用;已经取得了一些良好的进展,但似乎被卡住......需要PHP curl调用帮助

我们有接口(招摇),它允许我们做卷曲呼叫,测试它其中工程:这里是从卷曲命令:

curl -X POST --header "Content-Type: application/x-www-form-urlencoded" 
--header "Accept: application/json" 
--header "Authorization: Bearer xxxxx-xxxxxx- xxxxx-xxxxxxx" 
-d "username=xxxxxxxx39%40gmail.com&password=xxxx1234"  "http://xxxxxxxxx-xx-xx-201-115.compute-1.amazonaws.com:xxxx/api/users" 

,这里是我试图做同样的呼叫PHP代码:

$json = '{ 
"username": "xmanxxxxxx%40gmail.com", 
"password": "xxxx1234" 
}'; 


    $gtoken='xxxxxx-xxxxxx-xxx-xxxxxxxx'; 

$token_string="Authorization: Bearer ".$gtoken; 


$curl = curl_init(); 
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://exx-ccc-vvv-vvvv.compute-1.amazonaws.com:xxxx/api/users', //URL to the API 
CURLOPT_POST => true, 
CURLOPT_POSTFIELDS => $json, 
CURLOPT_HEADER => true, // Instead of the "-i" flag 
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded','Accept: application/json',$token_string) 

)); 

curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE); 

$resp = curl_exec($curl); 
curl_close($curl); 

我得到一个响应代码“500”,这让我觉得有什么不对我的输入。所以我想知道是否有人可以帮助...

回答

2

在您的命令行代码中,使用-d "username=xxxxxxxx39%40gmail.com&password=xxxx1234"发布标准的URL编码数据字符串,但在PHP中,您正在创建一个JSON字符串并将其作为单个帖子字段(没有正确的URL编码)。

我觉得这是你所需要的:

$data = array(
    'username' => '[email protected]', 
    'password' => 'xxxx1234', 
); 

$data = http_build_query($data); // convert array to urlencoded string 

curl_setopt($curl, CURLOPT_POSTFIELDS, $data); 

至于我可以告诉代码的其余部分看起来很好。

此外,您不明确需要设置Content-Type标头,当您将字符串传递给CURLOPT_POSTFIELDS时,cURL将为您执行此操作。如果你将一个数组传递给CURLOPT_POSTFIELDS,它会将它设置为multipart/form-data。但拥有它也不会伤害任何东西。

+0

你好德鲁:非常感谢你的回答,那就是诀窍,... –