douge7771 2014-10-30 16:12
浏览 64
已采纳

php-curl无法正常工作?

I am trying to send POST requests to Digitalocean's API v2 with cURL and custom headers but it is not working. I don't get any response, or the output/response I get is only:

Response from API:

My php code is:

<?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";
?>

Please tell me what's wrong in it? I have error reporting enabled.

  • 写回答

1条回答 默认 最新

  • dt97868 2014-10-30 16:24
    关注

    After looking at the $headers array more closely, I noticed you're sending your content as application/json, but at the same time, the postfields value does not match that content type. You'll probably have to add this:

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

    If that doesn't work, add the result of

    var_dump(curl_getinfo($ch));
    

    To your question, that'll tell you everything there is to know about the status of your curl request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看