简体   繁体   中英

php- curl is not working?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM