您好:我正在尝试使用curl_init进行API调用;取得了一些不错的进步,但似乎被卡住了...
我们有一个接口(swagger),允许我们执行curl调用并测试它是否有效:这是来自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”,使我认为输入内容有问题。所以我想知道是否有人可以帮助您...
在命令行代码中,您使用来发布标准URL编码的数据字符串,-d "username=xxxxxxxx39%40gmail.com&password=xxxx1234"
但在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
标题,当您将字符串传递给时,cURL会为您完成设置CURLOPT_POSTFIELDS
。multipart/form-data
如果您将数组传递给,它将设置为CURLOPT_POSTFIELDS
。但是拥有它也没有任何伤害。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句