代码之家  ›  专栏  ›  技术社区  ›  Andra

Google Cloud Vision API 400无效的JSON负载

  •  1
  • Andra  · 技术社区  · 7 年前

    当他们在中的协议部分写入时,我已经输入了所有必填字段 https://cloud.google.com/vision/docs/detecting-labels#vision-label-detection-protocol 当我在下面编写代码时。但是,它仍然返回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));
    ?>
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   dsesto    7 年前

    请求Cloud Vision API中唯一的错误是没有设置HTTP头字段的属性 内容类型:应用程序/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 ,其中有一些 nice documentation 通过脚本使用Google云平台中的一些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";
    }
    ?>