php-curl无法正常工作?

时间:2014-10-30 16:12:23

标签: php curl

我正在尝试使用cURL和自定义标头向Digitalocean的API v2发送POST请求,但它无法正常工作。我没有得到任何回复,或者我得到的输出/响应只是:

  

来自API的回应:

我的PHP代码是:

<?php
$TOKEN = "digitalocean api token";

$headers = array("Authorization: Bearer $TOKEN","Content-Type: application/json",);

 $name = "Test"; //droplet name
 $region = "nyc2"; //region
 $size = "512mb"; //size
 $image = "303022"; //replace it
 $user_data = "#!/bin/bash apt-get install nginx -y";

$postData = array(
'name' => $name,
'region' => $region,
'size' => $size,
'image' => $image,
'user_data' => $user_data,);

$post_body = '';
foreach($postData as $key => $value) {
$post_body.= urlencode($key) . '=' . urlencode($value) . '&';
}
$post_body = rtrim($post_body, '&');

$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, "https://api.digitalocean.com/v2/droplets");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
$result = curl_exec($ch);

echo "Response from API: $result";
?>

请告诉我它有什么问题?我启用了错误报告。

1 个答案:

答案 0 :(得分:1)

更仔细地查看$headers数组后,我发现您将内容发送为application/json,但同时,postfields值与该内容类型不匹配。您可能需要添加以下内容:

$postFields = json_encode($postData);
$headers[] = 'Content-Length: ' . strlen($postFields));
//set your opts
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);//json encoded string

如果不起作用,请添加

的结果
var_dump(curl_getinfo($ch));

对于您的问题,这将告诉您有关卷曲请求状态的所有信息。