Google Cloud Vision API 400 无效 JSON 负载

Google Cloud Vision API 400 Invalid JSON Payload

我已经输入了所有必填字段,因为他们在 https://cloud.google.com/vision/docs/detecting-labels#vision-label-detection-protocol 的协议部分写了我在下面写的代码。但是,还是 return 400 错误。

<?php
if(!isset($googleapikey)){
    include('settings.php');
}
function vision($query){
    global $googleapikey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,'https://vision.googleapis.com/v1/images:annotate?key='.$googleapikey);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
    $result = curl_exec ($ch);
    curl_close ($ch);
    return $result;
}

$vdata = array();
$vdata['requests'][0]['image']['source']['imageUri'] = 'https://cloud.google.com/vision/docs/images/ferris-wheel.jpg';
$vdata['requests'][0]['features'][0]['type'] = 'LABEL_DETECTION';
echo vision(json_encode($vdata));
?>

您在向 Cloud Vision API 请求中的唯一错误是您没有设置 属性 HTTP Header 字段 Content-type:application/json,因为你没有将它分配给正确的变量(你指向 $curl 而不是 $ch):

// Insread of this:
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
// Use this:
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));

当 运行 您的旧代码为以下代码时显示的错误,表明查询未将内容数据理解为 JSON。

Cannot bind query parameter. Field '{\"requests\":[{\"image\":{\"source\":{\"imageU ri\":\"https://cloud' could not be found in request message.

作为旁注,我向您推荐 Client Libraries for Cloud Vision API, which have some nice documentation,它可以让您在通过脚本使用 Google Cloud Platform 中的某些 API 时更轻松。在这种情况下,您不需要强制执行 curl 命令,并且可以使用更简单(且易于理解)的代码实现相同的结果,例如:

<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Vision\VisionClient;

$projectId = '<YOUR_PROJECT_ID>';
$vision = new VisionClient([
    'projectId' => $projectId
]);

$fileName = 'https://cloud.google.com/vision/docs/images/ferris-wheel.jpg';
$image = $vision->image(file_get_contents($fileName), ['LABEL_DETECTION']);
$labels = $vision->annotate($image)->labels();

echo "Labels:\n";
foreach ($labels as $label) {
    echo $label->description() . "\n";
}
?>