使用 curl 到 post 一个数组到 godaddy api

Using curl to post an array to the godaddy api

我正在尝试 post 将一堆域名发送给 godaddy api 以获得有关价格和可用性的信息。但是,每当我尝试使用 curl 执行此请求时,我什么都没有返回。我仔细检查了我的密钥凭据,最后一切似乎都是正确的。我非常有信心问题出在 post 字段的格式设置上,我只是不知道该怎么做...感谢提前提供帮助的人!

$header = array(
  'Authorization: sso-key ...'
);


$wordsArray = ['hello.com', "cheese.com", "bytheway.com"];
$url = "https://api.godaddy.com/v1/domains/available?checkType=FAST";


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); 
curl_setopt($ch, CURLOPT_POST, true); //Can be post, put, delete, etc.
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $wordsArray);

$result = curl_exec($ch);  
$dn = json_decode($result, true);
print_r($dn);

你的代码有两个问题:

  1. 发送数据的媒体类型必须是 application/json(默认情况下是 application/x-www-form-urlencoded),并且您的 PHP 应用程序必须接受 application/json 还有:
$headers = array(
    "Authorization: sso-key --your-api-key--",
    "Content-Type: application/json",
    "Accept: application/json"
);
  1. Post 字段必须指定为 JSON。为此,请使用 json_encode 函数:
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($wordsArray));

完整的 PHP 代码是:

$headers = array(
    "Authorization: sso-key --your-api-key--",
    "Content-Type: application/json", // POST as JSON
    "Accept: application/json" // Accept response as JSON
);


$wordsArray = ["hello.com", "cheese.com", "bytheway.com"];
$url = "https://api.godaddy.com/v1/domains/available?checkType=FAST";


$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($wordsArray));

$result = curl_exec($ch);

$dn = json_decode($result, true);
print_r($dn);